我想用jquery发布我的MVC表单。我的观点模型是这个
public class DemoViewModel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
我的控制器是
[HttpPost]
public JsonResult LongRunningDemoProcess(DemoViewModel model)
{
Thread.Sleep(1000);
return Json(model, "json");
}
我的视图有以下代码
@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测试验证,因为它已经包含在内。
感谢
答案 0 :(得分:8)
由于通过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();
});
这只是手动替换您对邮件的验证。
答案 1 :(得分:4)
我通过在我的捆绑包中加入jquery.validate.unobtrusive.js解决了这个问题
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*",
"~/Scripts/jquery.validate.unobtrusive.js"
));
并像这样检查
if ($("#myform").valid()) {
alert('not valid');
}
else{
// ajax logic
}