Ivy Ivy - 1 year ago 138
jQuery Question

Use ASP.NET MVC validation with jquery ajax?

I have simple ASP.NET MVC action like this :

public ActionResult Edit(EditPostViewModel data)


have validation attributes like this :

[Display(Name = "...", Description = "...")]
[StringLength(100, MinimumLength = 3, ErrorMessage = "...")]
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(

Now I got a couple of questions :

  1. 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

  2. Will the server side

  3. How can I forward validation problem back to the client and present it as if Im using the build int validation(

Example of Ajax call :

function SendPost(actionPath) {
url: actionPath,
type: 'POST',
dataType: 'json',
Text: $('#EditPostViewModel_Text').val(),
Title: $('#EditPostViewModel_Title').val()
success: function (data) {
error: function () {

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>

Answer Source

Client Side

Using the jQuery.validate library should be pretty simple to set up.

Specify the following settings in your Web.config file:

    <add key="ClientValidationEnabled" value="true"/> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 

When you build up your view, you would define things like this:

@Html.LabelFor(Model => Model.EditPostViewModel.Title, true)
@Html.TextBoxFor(Model => Model.EditPostViewModel.Title, 
                                new { @class = "tb1", @Style = "width:400px;" })
@Html.ValidationMessageFor(Model => Model.EditPostViewModel.Title)

NOTE: These need to be defined within a form element

Then you would need to include the following libraries:

<script src='@Url.Content("~/Scripts/jquery.validate.js")' type='text/javascript'></script>
<script src='@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")' type='text/javascript'></script>

This should be able to set you up for client side validation


Server Side

NOTE: This is only for additional server side validation on top of jQuery.validation library

Perhaps something like this could help:

public JsonResult Edit(EditPostViewModel data)
    //Save data
    return Json(new { Success = true } );

Where ValidateAjax is an attribute defined as:

public class ValidateAjaxAttribute : ActionFilterAttribute
    public override void OnActionExecuting(ActionExecutingContext filterContext)
        if (!filterContext.HttpContext.Request.IsAjaxRequest())

        var modelState = filterContext.Controller.ViewData.ModelState;
        if (!modelState.IsValid)
            var errorModel = 
                    from x in modelState.Keys
                    where modelState[x].Errors.Count > 0
                    select new
                               key = x,
                               errors = modelState[x].Errors.
                                                      Select(y => y.ErrorMessage).
            filterContext.Result = new JsonResult()
                                           Data = errorModel
            filterContext.HttpContext.Response.StatusCode = 
                                                  (int) HttpStatusCode.BadRequest;

What this does is return a JSON object specifying all of your model errors.

Example response would be

    "errors":["The Name field is required."]
    "errors":["The Description field is required."]

This would be returned to your error handling callback of the $.ajax call

You 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