开发者

Ajax form validation

Is there any convenient way to integrate ASP.NE开发者_运维技巧T MVC validation (I am primarily interested in Fluent Validation) with forms submitting by Ajax?


The easiest way to achieve this is to place those forms inside partials and then submit them using AJAX. The controller action which will handle the POST will check if the model is valid and if not return the partial in order to show the validation errors. For example:

<div id="myform_container">
    <!-- The _Foo partial will contain a form -->
    @Html.Partial("_Foo")
</div>

and a controller action which will handle the submission:

[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 });
}

Now all that's left is to AJAXify this form in a separate javascript file:

$(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;
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜