2010-01-17 9 views
1

일종의 Multibinders를 사용할 수 있습니까? 나는 또한이 같은 기본 바인더를 구성ASP.NET MVC : 다중 모델 바인딩

[Authorize] 
[AcceptVerbs("POST")] 
public ActionResult Edit([CustomBinder]MyObject obj) 
{ 
    ///Do sth. 
} 

:

protected void Application_Start() 
    { 
     log4net.Config.XmlConfigurator.Configure(); 
     RegisterRoutes(RouteTable.Routes); 

     ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder(); 
    } 

내가 원하는 것은 (등 stringlength, regexps '에 대한 데이터 유효성을 검사)를 DataAnnotationsBinder의 장점을 가지고 있으며 추가 필드 값을 설정하는 내 사용자 정의 바인더.

나는 EntitiyFramework하고 같이 contstruct 초래 DataAnnotations와 함께 사용하여 스피로,이 만 1 바인더를 쓸 수 없습니다 :

[MetadataType(typeof(MyObjectMetaData))] 
    public partial class MyObject 
    { 
    } 


    public class MyObjectMetaData 
    { 
    [Required] 
    [StringLength(5)] 
    public object Storename { get; set; } 
    } 

답변

1

은 당신의 기본 모델 바인더를 호출 시도 할 수 있습니다 당신의 사용자 정의 모델 바인더.

public class CustomBinder : IModelBinder { 
    public object BindModel(ControllerContext controllerContext, 
    ModelBindingContext bindingContext) { 
     MyObject o = (MyObject)ModelBinders.Binders 
      .DefaultBinder.BindModel(controllerContext, bindingContext); 
     //Your validation goes here. 
     return o; 
    } 
} 
1

왜 DataAnnotationsModelBinder에서 상속하지 않습니까?

public class MyBinder : DataAnnotationsModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     MyModel obj = (MyModel)base.BindModel(controllerContext, bindingContext); 
     //Do your operations 
     return obj; 
    } 
} 

ModelBinders.Binders[typeof(MyModel)] = new MyBinder();