开发者

I need a DataAnnotationsModelBinder for DataAnnotations v 3.5

开发者 https://www.devze.com 2022-12-11 19:34 出处:网络
I need a DataAnnotationsModelBinder that is going to work开发者_运维知识库 with System.ComponentModel.DataAnnotations v 3.5i have found one on codeplex, but is for the v 0.99 of DataAnnotations and it

I need a DataAnnotationsModelBinder that is going to work开发者_运维知识库 with System.ComponentModel.DataAnnotations v 3.5

i have found one on codeplex, but is for the v 0.99 of DataAnnotations and it doesn't work with v 3.5, and my xVal doesn't work with DataAnnotations v 0.99, so i'm kinda stuck


This is a fairly naive model binder, but it might be what you are looking for.

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

精彩评论

暂无评论...
验证码 换一张
取 消