Validating a form asynchronously using jquery in MVC
less than a minute read
A common requirement that is often requested in modern sites is for forms to be submitted and validated on asynchronously. This was also a question posed by @troyhunt recently.
Here is my usual approach to the problem using MVC4.
First thing we need is a form. This form sits in a partial view (Create.cshtml)
@using (Html.BeginForm()
{
<div>
// Add validation summary
@Html.ValidationSummary(false)
</div>
<div>
@Html.LabelFor(m => m.Property1)
@Html.TextBoxFor(m => m.Property1)
</div>
<div>
@Html.LabelFor(m => m.Property2)
@Html.TextBoxFor(m => m.Property2)
</div>
<button id="submit-button" type="submit" value="Submit" />
The partial view is then placed inside a containing div on the main page
<div id="form-container">
@Html.Partial("Create")
</div>
Our post action is like any other, except for one thing. If all validation passes we return "success" as a string
[HttpPost]
public ActionResult Create(ViewModel viewModel)
{
// Check model is valid
if (!ModelState.IsValid)
{
//Return the form with validation errors
return this.PartialView(viewModel);
}
//TODO: Perform success action
return Content("success");
}
Finally, we have our javascript which will perform the post action<br />
@section scripts
{
<script type="text/javascript">
$(function() {
$('#submit-button').on('click', function() {
var form = $('#form-container form');
var postUrl = form.attr('action');
var postData = form.serialize();
$.post(postUrl, postData, function (data) {
if (data == 'success') {
//TODO: Add success action
} else {
$('#form-container').html(data);
}
});
});
})
</script>
}