Мне нужен DataAnnotationsModelBinder для DataAnnotations v 3.5

Мне нужен DataAnnotationsModelBinder, который будет работать с System.ComponentModel.DataAnnotations v 3.5
Я нашел один в codeplex, но для v 0.99 DataAnnotations и он не работает с v 3.5, и мой xVal не работает с DataAnnotations v 0.99, поэтому я немного застрял

1 ответ

Решение

Это довольно наивный модельный переплет, но это может быть то, что вы ищете.

public class DataAnnotatedModelBinder : IModelBinder
{
    private IModelBinder _defaultBinder = new DefaultModelBinder();


    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    {
        var boundInstance = _defaultBinder.BindModel(controllerContext, bindingContext);

        if (boundInstance != null) {
            PerformValidation(boundInstance, bindingContext);
        }

        return boundInstance;
    }

    protected void PerformValidation(object instance, ModelBindingContext context) 
    {
        var errors = GetErrors(instance);

        if (errors.Any())
        {
            var rulesException = new RulesException(errors);

            rulesException.AddModelStateErrors(context.ModelState, null);
        }
    }

    public static IEnumerable<ErrorInfo> GetErrors(object instance)
    {
        return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
               from attribute in prop.Attributes.OfType<ValidationAttribute>()
               where !attribute.IsValid(prop.GetValue(instance))
               select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(String.Empty), instance);
    }
}
Другие вопросы по тегам