Assuming you are using jQuery validation, which comes with MVC solution templates, in your javascript handler you will have to add errors to the validator. There is a showErrors method on the validator .
On the client side :
var formSubmitCallback = function(result){ var validator = $(this).data('validator'); if(!result.IsValid && validator) validator.showErrors(result.Errors);
Now I had to standardize the result object from the server to return a json object formatted with { "FieleName": "Error Message" } . I built several Controller and ViewModel extensions on the server side to accomplish this.
On the server side :
public ActionResult SomeAction(Model someModel){ if(ModelState.IsValid) // save else // other stuff // always return this.AjaxSubmit. // Extension function will add Errors, and IsValid to the response data return this.AjaxSubmit(new ClientAction{ Action = ClientActionType.Redirect, Url = "/Some/Redirect/Route" }); }
Note: looking back, I wrote some custom code to make it work. In the end, I will add the client and server code along with examples on github. But this is a general idea.
The server classes and extension you will need are below
// GetAllErrors is a ModelState extension to format Model errors for Json response public static Dictionary<string, string> GetAllErrors(this ModelStateDictionary modelState) { var query = (from state in modelState where state.Value.Errors.Count > 0 group state by state.Key into g select new { FieldName = g.Key, FieldErrors = g.Select(prop => prop.Value.Errors).First().Select(prop => prop.ErrorMessage).ToList() }); return query.ToDictionary(k => k.FieldName, v => string.Join("<br/>", v.FieldErrors)); } // Controller result extension to return from actions public static JsonResult AjaxSubmit(this Controller controller, ClientAction action) { if (controller == null) return new JsonResult { Data = action }; var result = new AjaxSubmitResult { Errors = controller.ModelState.GetAllErrors(), IsValid = controller.ModelState.IsValid, ClientAction = action }; return new JsonResult{ Data = result }; } // Action to perform on the client after a successful, valid response public class ClientAction { public ClientActionType Action { get; set; } public string Url { get; set; } public string Function { get; set; } public object Data { get; set; } public Dictionary<string, string> Updatables { get; set; } } public enum ClientActionType { Redirect, Ajax, Function, Modal, Message, FunctionAndMessage }
source share