I have simple ASP.NET MVC action like this :
public ActionResult Edit(EditPostViewModel data)
{
}
The EditPostViewModel
have validation attributes like this :
[Display(Name = "...", Description = "...")]
[StringLength(100, MinimumLength = 3, ErrorMessage = "...")]
[Required()]
public string Title { get; set; }
In the view I am using the following helpers :
@Html.LabelFor(Model => Model.EditPostViewModel.Title, true)
@Html.TextBoxFor(Model => Model.EditPostViewModel.Title,
new { @class = "tb1", @Style = "width:400px;" })
If I do a submit on a form that this textbox is placed in a validation will be done first on client and then on service(ModelState.IsValid
).
Now I got a couple of questions :
Can this be used with jQuery ajax submit instead? What I am doing is simply remove the form and on clicking the submit button a javascript will gather data and then run the
$.ajax
.Will the server side
ModelState.IsValid
work?How can I forward validation problem back to the client and present it as if Im using the build int validation(
@Html.ValidationSummary(true)
)?
Example of Ajax call :
function SendPost(actionPath) {
$.ajax({
url: actionPath,
type: 'POST',
dataType: 'json',
data:
{
Text: $('#EditPostViewModel_Text').val(),
Title: $('#EditPostViewModel_Title').val()
},
success: function (data) {
alert('success');
},
error: function () {
alert('error');
}
});
}
Edit 1:
Included on page :
<script src="/Scripts/jquery-1.7.1.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>