0
是否有任何方便的方式将ASP.NET MVC验证(我主要关注Fluent验证)与Ajax提交的表单进行整合?Ajax表单验证
是否有任何方便的方式将ASP.NET MVC验证(我主要关注Fluent验证)与Ajax提交的表单进行整合?Ajax表单验证
实现此目的的最简单方法是将这些表单放入partial中,然后使用AJAX提交它们。将处理POST的控制器操作将检查模型是否有效,如果不返回该部分以显示验证错误。例如:
<div id="myform_container">
<!-- The _Foo partial will contain a form -->
@Html.Partial("_Foo")
</div>
和控制器动作,将处理提交:
[HttpPost]
public ActionResult Foo(SomeViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView("_Foo", model);
}
// TODO: process the results and inform the user that everything went fine:
return Json(new { success = true });
}
现在,所有剩下的就是在一个单独的JavaScript文件到AJAXify这种形式:
$(function() {
// Use delegate to preserve the .submit handler when we refresh the container
$('#myform_container').delegate('form', 'submit', function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
if (result.success) {
// the server returned JSON
alert('thanks for submitting');
} else {
// the server returned the partial => update the DOM
$('#myform_container').html(result);
}
}
});
return false;
});
});