Last active
October 23, 2015 19:28
-
-
Save EfrainReyes/e8b03e647b116d91192a to your computer and use it in GitHub Desktop.
Use MVC's model state on Ajax forms, provided that there's some client-side code to capture the validation output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// http://stackoverflow.com/questions/14005773/use-asp-net-mvc-validation-with-jquery-ajax | |
/// </summary> | |
public class ValidateAjaxAttribute : ActionFilterAttribute, IExceptionFilter | |
{ | |
public override void OnActionExecuting(ActionExecutingContext filterContext) { | |
if(!filterContext.HttpContext.Request.IsAjaxRequest()) { | |
return; | |
} | |
var modelState = filterContext.Controller.ViewData.ModelState; | |
if (modelState.IsValid) { | |
return; | |
} | |
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; | |
filterContext.Result = GetModelErrorData(modelState); | |
} | |
public override void OnActionExecuted(ActionExecutedContext filterContext) { | |
if(!filterContext.HttpContext.Request.IsAjaxRequest()) { | |
return; | |
} | |
var modelState = filterContext.Controller.ViewData.ModelState; | |
if (modelState.IsValid) { | |
return; | |
} | |
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; | |
filterContext.Result = GetModelErrorData(modelState); | |
} | |
public void OnException(ExceptionContext filterContext) { | |
if (!filterContext.HttpContext.Request.IsAjaxRequest()) | |
return; | |
var modelState = filterContext.Controller.ViewData.ModelState; | |
var exception = filterContext.Exception as CustomException; | |
if (exception != null) { | |
modelState.AddModelError(exception.PropertyName, exception.Message); | |
} | |
else { | |
modelState.AddModelError(string.Empty, Resources.APPLICATION_ERROR); | |
} | |
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; | |
filterContext.Result = GetModelErrorData(modelState); | |
filterContext.ExceptionHandled = true; | |
} | |
private static JsonNetResult GetModelErrorData(IDictionary<string, ModelState> modelState) { | |
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). | |
ToArray() | |
}; | |
return new JsonNetResult(new JsonSerializerSettings() { Formatting = Formatting.Indented }) { | |
Data = errorModel | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment