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 stuckThis 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);
}
}
精彩评论