Created
June 24, 2013 16:40
-
-
Save jjvdangelo/5851487 to your computer and use it in GitHub Desktop.
Allows HttpGet decorated controllers to display model errors.
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
namespace Attributes | |
{ | |
using System.Web.Mvc; | |
public class DisplayModelErrorsAttribute : ActionFilterAttribute | |
{ | |
public override void OnActionExecuted(ActionExecutedContext filterContext) | |
{ | |
var model = filterContext.Controller.ViewData.Model; | |
var metadatas = ModelMetadataProviders.Current.GetMetadataForProperties(model, model.GetType()); | |
var modelState = filterContext.Controller.ViewData.ModelState; | |
foreach (var metadata in metadatas) | |
{ | |
var validator = ModelValidator.GetModelValidator(metadata, filterContext.Controller.ControllerContext); | |
foreach (var error in validator.Validate(model)) | |
{ | |
var propName = metadata.PropertyName + "." + error.MemberName; | |
modelState.AddModelError(propName, error.Message); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment