Asp.net mvc 我需要一个DataAnnotationsModelBinder用于DataAnnotationsV3.5

Asp.net mvc 我需要一个DataAnnotationsModelBinder用于DataAnnotationsV3.5,asp.net-mvc,modelbinders,Asp.net Mvc,Modelbinders,我需要一个DataAnnotationsModelBinder,它将与System.ComponentModel.DataAnnotationsV3.5一起使用我在codeplex上找到了一个,但它适用于DataAnnotations的V0.99,不适用于V3.5,我的xVal不适用于DataAnnotationsV0.99,所以我有点卡住了这是一个相当幼稚的模型绑定器,但它可能是你正在寻找的 public class DataAnnotatedModelBinder : IModelBinde

我需要一个DataAnnotationsModelBinder,它将与System.ComponentModel.DataAnnotationsV3.5一起使用
我在codeplex上找到了一个,但它适用于DataAnnotations的V0.99,不适用于V3.5,我的xVal不适用于DataAnnotationsV0.99,所以我有点卡住了

这是一个相当幼稚的模型绑定器,但它可能是你正在寻找的

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);
    }
}
公共类DataAnnotatedModelBinder:IModelBinder
{
私有IModelBinder_defaultBinder=新的DefaultModelBinder();
公共对象绑定模型(ControllerContext ControllerContext,ModelBindingContext bindingContext)
{
var boundInstance=_defaultBinder.BindModel(controllerContext,bindingContext);
if(boundInstance!=null){
执行验证(boundInstance、bindingContext);
}
返回边界实例;
}
受保护的void性能验证(对象实例、ModelBindingContext上下文)
{
var errors=GetErrors(实例);
if(errors.Any())
{
var rulesException=新的rulesException(错误);
rulesException.AddModelStateErrors(context.ModelState,null);
}
}
公共静态IEnumerable GetErrors(对象实例)
{
从TypeDescriptor.GetProperties(instance.Cast()中的prop返回
来自类型()的prop.Attributes.of中的属性
其中!attribute.IsValid(prop.GetValue(实例))
选择新的ErrorInfo(prop.Name,attribute.FormatErrorMessage(String.Empty),instance);
}
}