Sunday, 25 August 2013

jquery post still goes through inspite of asp.net mvc 4 validation failure

jquery post still goes through inspite of asp.net mvc 4 validation failure

I want an asp.net mvc form to post to a controller and also show a message
on error or success, all of which using jquery. I want this jquery post to
happen only if the form validation is successful. The problem is that the
post happens even when the form validation has failed. I am using Data
annotations in the mvc framework to validate. Here is the code
View
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet"
type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.8.3.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
<div>
@using ( Html.BeginForm("jQueryPost", "Home",null, FormMethod.Post,
new { id="FormPost" }))
{
@Html.TextBoxFor(x => x.Name) @Html.ValidationMessageFor(x => x.Name)
<br />
@Html.TextBoxFor(x => x.LastName) @Html.ValidationMessageFor(x =>
x.LastName)
<br />
@Html.TextBoxFor(x => x.Age) @Html.ValidationMessageFor(x => x.Age)
<br />
<input type=submit value="submit" />
}
</div>
<script>
$(document).ready(function () {
$('#FormPost').submit(function (e) {
e.preventDefault(); //This line will prevent the form from
submitting
alert('ajax post here');
$.ajax({
type: 'POST',
url: $('#FormPost').attr('action'),
data: $('#FormPost').serialize(),
accept: 'application/json',
error: function (xhr, status, error) {
alert('error: ' + xhr.responseText + '-' + error);
},
success: function (response) {
alert('resp: ' + response);
}
});
});
});
</script>
The Controller
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult jQueryPost(IndexVM vm)
{
IndexVM _vm = vm;
try
{
//some code here
}
catch
{
Response.StatusCode = 406; // Or any other proper status code.
Response.Write("Custom error message");
return null;
}
return Json("name posted was: " + _vm.Name);
}

No comments:

Post a Comment