2009-11-16 4 views
0

J'ai besoin d'un DataAnnotationsModelBinder qui va fonctionner avec System.ComponentModel.DataAnnotations v 3.5
j'en ai trouvé un sur codeplex, mais pour la version 0.99 de DataAnnotations et ça ne marche pas avec v 3.5, et mon xVal ne fonctionne pas avec DataAnnotations v 0.99, donc je suis un peu coincéJ'ai besoin d'un DataAnnotationsModelBinder pour DataAnnotations v 3.5

Répondre

2

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

thnx homme, ça m'a vraiment aidé :) – Omu