0

Is there any convenient way to integrate ASP.NET MVC validation (I am primarily interested in Fluent Validation) with forms submitting by Ajax?

1 Answer 1

1

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;
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.