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>
Best Answer
Client Side
Using the
jQuery.validate
library should be pretty simple to set up.Specify the following settings in your
Web.config
file:When you build up your view, you would define things like this:
NOTE: These need to be defined within a form element
Then you would need to include the following libraries:
This should be able to set you up for client side validation
Resources
Server Side
NOTE: This is only for additional server side validation on top of
jQuery.validation
libraryPerhaps something like this could help:
Where
ValidateAjax
is an attribute defined as:What this does is return a JSON object specifying all of your model errors.
Example response would be
This would be returned to your error handling callback of the
$.ajax
callYou can loop through the returned data to set the error messages as needed based on the Keys returned (I think something like
$('input[name="' + err.key + '"]')
would find your input element