1

We have a number of forms on our site that are shown with jquery .dialog and we submit them using an ajax post request.

I've done a fair bit of research and from what I can tell there isn't any definite patterns on how to return validation errors from the server side as a result of an ajax request.

Pretty much the only pattern I could find was to post the form and then do validation server side and in either case return a json object that encapsulated a result and if the result was incorrect the form html

ie.

{result: true}
{success: false, html =  "<form>....</form>"}

So in the case the result was false you would need to rewire up any events attached to items on the form as you would be replacing the old form with the new form that has the validation errors.

This seems like an ok approach but you also end up potentially returning a lot more data to the client that you need to when they only really need to validation messages and you are also forced to rewire the form up which is a bit annoying.

I did find one other mention of somehow getting the validation errors and returning them in a json object from the action and somehow telling the client to display them against the correct fields.

Is there any frameworks out there that make this easier or should I write my own or just stick to returning the entire partial for the form and rewiring it when validation is incorrect?

1 Answer 1

2

I don't know of any frameworks that handle this particular case–and I don't know that there's a clear best practice–but it's easy enough to serialize validation errors and return them as a JSON object. You could try this extension method on ModelStateDictionary:

public static IEnumerable<ValidationResult> GetValidationResults(this ModelStateDictionary dictionary)
{
    foreach (var key in dictionary.Keys)
        foreach (var error in dictionary[key].Errors)
            if (error != null)
                yield return new ValidationResult(error.ErrorMessage, new string[] { key });
}

And in the controller:

if (!ModelState.IsValid)
{
    return new JsonResult(ModelState.GetValidationResults());
}

But you're right, you would then have to loop through the object and append the errors to the correct fields. If you have ClientValidationEnabled and UnobtrusiveJavaScriptEnabled set to true, the loop would look something like this:

$.each(errors, function(i, item) {
    $('span[data-valmsg-for=' + item.MemberNames[0] + ']').html(item.ErrorMessage);
})

If not, it wouldn't be that difficult to match up the error messages to their respective fields as the object contains the field name. This would definitely save you some data across the wire, but it moves a larger share of the validation responsibility into Javascript. Like I said, I don't know that there's a clear best practice, but I have used this method in the past with success.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm going to take this approach but instead of looping through each errors I have found if you are using jquery validate you can pass them to validator.showErrors() if you have them in the correct json format

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.