Skip to content

Instantly share code, notes, and snippets.

@jjvdangelo
Created June 24, 2013 16:40
Show Gist options
  • Save jjvdangelo/5851487 to your computer and use it in GitHub Desktop.
Save jjvdangelo/5851487 to your computer and use it in GitHub Desktop.
Allows HttpGet decorated controllers to display model errors.
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