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
views:
157answers:
1
+2
A:
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);
}
}
mkedobbs
2009-11-16 20:38:41
thnx man, that really helped :)
Omu
2009-11-17 07:25:06