Question

I have been looking at many ASP.Net MVC client side validation ideas including xVal. This doesn't provide a ValidationSummary at the moment so I chose to do an AJAX post which loops through ModelState errors and update a DIV with the error messages on a successful AJAX post.

The problem with this is your ValidationMessage * next to the fields won't get populated. I have come up with an alternative idea which I haven't yet tested as I don't know the full syntax to get it working yet but thought I'd see what you guys thought.

One issue I think may be an issue is that when you post to your Edit/Create Action method in the controller and you want to return a JSON object, I'm not sure that is legal as JSON is used for GET actions only.

If you think its a good idea and are wanting to help please leave an answer and any code snippets to get this working. If you think its a hair brained scheme and can be done better please let me know how.

Controller:

if (!ModelState.IsValid)
{
            var err = ModelState.Where(f => f.Value.Errors.Count > 0);    
            if (Request.IsAjaxRequest())
            {
                   return this.Json(err);
            }
            else
            {
                  return View(PostedItem); 
            }
}

View:

    $(function() {



    $('#createForm').ajaxForm({
        success:fillSummary
    });

    //click events
    $('#btnSave').click( function(){
        $('#createForm').submit();
    });

    function fillSummary(data) 
    {
       //Loop through the modelstate errors returned
        $.each(data)
       {
            //Append Summary DIV with error message
            //Look for span with the ModelState key name and set it to visible
       }           
    }



    <div id="summary">
       <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.")%>
    </div>
    <form action="<%=Url.Action("Create") %>" method="post" id="createForm">

        <fieldset>
            <div>
                 <label for="Title">Title:</label>
                <%= Html.TextBox("Title",Model.Title) %>
                <%= Html.ValidationMessage("Title", "*") %>
                <span id="val_Title" style="display:none">*</span>              
            </div>
   </form>
   <input type="button" value="Save" id="btnSave" />
Was it helpful?

Solution

In my current ASP.NET MVC project I have a lot of POST actions that I use for AJAX and ran across the validation issue too. What I did was create a wrapper object that gets returned from each of these actions which looks something like this...

public class JsonWrapper
{
   public object Data { get; set; }
   public bool IsError { get; set; }
   public string Message { get; set; }
}

If the validation in the action doesn't have any kind of errors, I place whatever data I want to return in the Data property. However, if there's any kind of validation error or other exception, I set the IsError flag to true and set an error message in the Message property. Then at the end of the action, I serialize the object to JSON and return it, (yes you can do this from a POST action)...

return Json(myJsonWrapper);

From the client side, in the onSuccess of my AJAX POST code, I check for errors, and take any actions neccessary like this... (Note, at this point in the code, the object that got returned from the server has already been deserialized into a JS object by jQuery)

function onSuccess(jsonWrapper) {
    if (!jsonWrapper.IsError) {
        var myDataFromAction = jsonWrapper.Data;
        //Do stuff with my data
    }
    else {
        MessageBox.ShowMessage(jsonWrapper.Message);
    }
}

This won't fit your scenario out of the box, but you could do something similar as a concept. Hope this at least gives you some ideas.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top