2009-11-16 36 views
0

我需要一個DataAnnotationsModelBinder,它將與System.ComponentModel.DataAnnotations v 3.5
一起使用我已經在codeplex上找到一個,但是對於DataAnnotations v 0.99並且它不起作用用v 3.5,我XVAL不起作用與DataAnnotations v 0.99,所以我有點堅持我需要一個DataAnnotationsModelBinder DataAnnotations v 3.5

回答

2

這是一個相當幼稚的模型綁定,但它可能是你在找什麼。

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的人,真正幫助:) – Omu 2009-11-17 07:25:06