有没有方便的方法将ASP.NET MVC验证(我主要对Fluent验证感兴趣)与Ajax提交的表单集成?
答案 0 :(得分:1)
实现此目的的最简单方法是将这些表单放在partials中,然后使用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;
});
});