I\'m developing a web app with asp.net mvc 3 and I have some form that POST to an async action (via ajax). This action recives a ViewModel with some data annotations to validate
Instead of sending JSON in case of error I would put the form inside a partial and then have the controller action return this partial in case of error. The problem with JSON is that you could in fact fetch the errors from the ModelState using LINQ, but it could be a PITA to show them on the view.
So:
@Html.Partial("_MyForm")
and then inside _MyForm.cshtml
:
@model CustomerViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)
@Html.EditorFor(x => x.Bar)
@Html.ValidationMessageFor(x => x.Bar)
}
and the controller action would become:
[HttpPost]
public ActionResult SaveCustomer(CustomerViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView("_MyForm", model);
}
return Json(new { success = true });
}
and the last step is to AJAXify this form which could be done in a separate javascript file:
$(function () {
$('#myform').delegate('form', 'submit', function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
// We have a JSON object in case of success
alert('success');
} else {
// We have the partial with errors in case of failure
// so all we have to do is update the DOM
$('#myform').html(result);
}
}
});
return false;
});
});