我想用 jquery 发布我的 MVC 表单。我的 View 模型是这样的
public class DemoViewModel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
我的 Controller 是
[HttpPost]
public JsonResult LongRunningDemoProcess(DemoViewModel model)
{
Thread.Sleep(1000);
return Json(model, "json");
}
我的 View 有以下代码
@model WebApplication2.Models.DemoViewModel
@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm("LongRunningDemoProcess", "Home", FormMethod.Post,
new { encType = "multipart/form-data", id = "myform", name = "myform" }))
{
<div class="form-group">
@Html.LabelFor(model => model.FirstName,
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName,
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
<input type="submit" name="operation" id="process" value="process" />
}
<div id="divProcessing">
<p>Processing, please wait . . . <img src="../../Content/ajax-loader.gif"></p>
</div>
<div id="divResult">
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
// Hide the "busy" Gif at load:
$("#divProcessing").hide();
// Handle the form submit event, and make the Ajax request:
$("#myform").on("submit", function (event) {
event.preventDefault();
// Show the "busy" Gif:
$("#divProcessing").show();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax({
url: url,
type: "POST",
data: formData,
dataType: "json",
success: function (resp) {
// Hide the "busy" gif:
$("#divProcessing").hide();
// Do something useful with the data:
$("<h3>" + resp.FirstName + " " + resp.LastName + "</h3>").appendTo("#divResult");
}
})
});
});
</script>
}
但问题是,即使它们是必填字段的错误,表单也会发布并获取结果
我尝试测试此代码 if($("#myform").valid())
但没有可用的方法。
如何使用 jquery.validate.js 测试验证,因为它已经包含在内。
谢谢
最佳答案
由于通过ajax提交表单,您必须手动调用它。
这是您可以采取的一种方法:
$.validator.unobtrusive.parse($form);
$form.validate();
if ($form.valid()) {
// ajax call
}
else {
// Failed show errors
}
如果失败,错误将包含在 $form.validate().errorList
中,但您必须手动解析它们。
您可以按如下方式执行此操作:
$.each($form.validate().errorList, function (key, value) {
$errorSpan = $("span[data-valmsg-for='" + value.element.id + "']");
$errorSpan.html("<span style='color:red'>" + value.message + "</span>");
$errorSpan.show();
});
这只是取代您手动验证消息。
关于jquery - 在 asp.net mvc 5 中发布之前使用 jquery 检查所有验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29008679/