I am trying to send and validate a form via jquery ajax. I would like to know if it is possible and how to achieve this.
What do I have?
View:
@using (Html.BeginForm("Index", "Home"))
{
<section id="result">
@Html.ValidationSummary(false)
</section>
<section>
@Html.LabelFor(model => model.Isbn)
@Html.TextBoxFor(model => model.Isbn)
@Html.ValidationMessageFor(model => model.Isbn)
</section>
<section>
@Html.LabelFor(model => model.BookNumber)
@Html.TextBoxFor(model => model.BookNumber)
@Html.ValidationMessageFor(model => model.BookNumber)
</section>
<section>
@Html.LabelFor(model => model.Title)
@Html.TextBoxFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</section>
<section>
@Html.LabelFor(model => model.ReleaseDate)
@Html.TextBoxFor(model => model.ReleaseDate)
@Html.ValidationMessageFor(model => model.ReleaseDate)
</section>
<button type="submit">Go</button>
}
My javascript:
<script>
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize()
})
.success(function (result) {
$('#result').html(result);
})
.error(function () {
alert("oops! some critical stuff");
});
}
return false;
});
});
</script>
At last, my controller:
[HttpPost]
public ActionResult Index(Book model)
{
if (!ModelState.IsValid)
return View(model);
if (model.Title.IsEmpty())
{
ModelState.AddModelError("Title", "What are you doing?? The title can't be emtpy!");
return View(model);
}
return View();
}
So, this is just a case study. I wanted to have the DataAnnotations working on the client side, which already are. And when I post the form to the server, perform some more validations via ModelState.IsValid and ModelState.AddModelError and have this shown back to the client.
Is it possible to accomplish this?