2011-02-05 76 views
1

我有一個看起來像這樣的動作:默認模型聯編程序總是創建一個實例?

public ActionResult Index(Home document) { 

     return View(new BaseViewModel<Home>(document, _repository)); 
    } 

但即使RouteData.Values [「文件」]不存在模型綁定創建主頁的一個實例。如果文檔爲空,是否可以告訴模型聯編程序給我null?

回答

2

,如果你想改變這種默認行爲,您可能需要自定義模型粘合劑:

public class MyModelBinder : DefaultModelBinder 
{ 
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) 
    { 
     // TODO: decide if you need to instantiate or not the model 
     // based on the context 
     if (!ShouldInstantiateModel) 
     { 
      return null; 
     } 
     return base.CreateModel(controllerContext, bindingContext, modelType); 
    } 
} 

然後:

public ActionResult Index([ModelBinder(typeof(MyModelBinder))] Home document) 
{ 
    return View(new BaseViewModel<Home>(document, _repository)); 
} 

Application_Start全球範圍內進行註冊:

ModelBinders.Binders.Add(typeof(Home), new MyModelBinder()); 
+0

再次感謝 – Marcus 2011-02-05 17:26:43

相關問題