2010-01-17 181 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(); 
    } 

我想是有DataAnnotationsBinder(這驗證了數據stringlength,正則表達式等)的好處,另外我的自定義活頁夾設置字段值。

我不能只寫1粘結劑這一點,因爲使用EntitiyFramework並與它導致contstruct這樣的DataAnnotations組合IAM:

[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();