Ceci est un classeur modèle assez naïf, mais il pourrait être ce que vous cherchez.
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);
}
}
thnx homme, ça m'a vraiment aidé :) – Omu