Created
November 28, 2014 03:17
-
-
Save EfrainReyes/ef6cfcc4c9800f075a3a to your computer and use it in GitHub Desktop.
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
public class ModelStateValidationAttribute : ActionFilterAttribute, IExceptionFilter | |
{ | |
public override void OnActionExecuting(ActionExecutingContext filterContext) { | |
if(filterContext.HttpContext.Request.IsAjaxRequest()) | |
return; | |
var modelIsValid = filterContext.Controller.ViewData.ModelState.IsValid; | |
if(!modelIsValid) { | |
filterContext.Result = new ViewResult() { | |
ViewData = filterContext.Controller.ViewData | |
}; | |
} | |
} | |
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.Result = new ViewResult { | |
ViewData = filterContext.Controller.ViewData, | |
TempData = filterContext.Controller.TempData | |
}; | |
filterContext.ExceptionHandled = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment