我需要一个DataAnnotationsModelBinder for DataAnnotations v 3.5

时间:2009-11-16 18:38:52

标签: asp.net-mvc modelbinders

我需要一个DataAnnotationsModelBinder,它将与System.ComponentModel.DataAnnotations v 3.5一起使用。我在codeplex上找到了一个,但是对于V的0.99的DataAnnotations并且它不适用于v 3.5,并且我的xVal无法使用DataAnnotations v 0.99,所以我有点卡住了

1 个答案:

答案 0 :(得分:2)

这是一个相当天真的模型绑定器,但它可能正是您正在寻找的。

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);
    }
}