Assuming you are using jQuery validate that comes with MVC solution templates, in your javascript handler you will have to add errors to the validator. There is a showErrors
method on validator.
On the client side:
var formSubmitCallback = function(result){
var validator = $(this).data('validator');
if(!result.IsValid && validator)
validator.showErrors(result.Errors); // uses jquery validator to highlight the fields
// process the rest of the result here
// if result.Action == ActionTypes.Redirect
// location.href = result.Url
// etc
}
Now I had to standardize the result object from the server to return a json object formatted with { "FieleName": "Error Message" }
. I built a few Controller
and ViewModel
extension on the server side to accomplish that.
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 on this now I did write a bit of custom code to make it work. I will eventually add the client and server code, together with examples on github. But this is the 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
}