2009-11-16 2 views
0

System.ComponentModel.DataAnnotations와 함께 작동 할 DataAnnotationsModelBinder가 필요합니다. 3.5
코드 플렉스에서 하나를 찾았지만 DataAnnotations가 0.99이고 작동하지 않습니다. v 3.5에서는 xVal이 DataAnnotations v 0.99와 함께 작동하지 않습니다. 따라서 다소 붙어 있습니다.DataAnnotations에 대해 DataAnnotationsModelBinder가 필요합니다. 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