3

我並沒有把握MVC模型的一些概念基礎知識,我希望有一些有用的說明。MVC Model Instantiation

在我的MVC 4 Web應用程序,我有建立一個IEnumerable <SelectListItem>爲一個DropDownList視圖模型,如果我這樣做,我認爲:

@model MyApp.Models.MyModel 

@Html.DropDownListFor(x => x.MyThingID, Model.MySelectList, "Select...") 

我得到一個「未將對象引用設置爲一個對象的實例「錯誤。

但是,如果我這樣做:

@model MyApp.Models.MyModel 

@{ var myModel = new MyApp.Models.MyModel(); } 
@Html.DropDownListFor(x => x.MyThingID, myModel.MySelectList, "Select...") 

它的工作原理。但是這個顯式的實例化看起來和感覺對我來說是非常錯誤的,我不確定我是否應該在控制器中做任何事情,在這裏,這只是一個簡單的「返回View()」ActionResult。

我找不到太多好的指導,最終我試圖實現一些級聯下拉菜單,所以我需要更好地掌握它的工作原理。如果您有時間和傾向來協助,我將不勝感激。

回答

2

您應該將模型傳遞給視圖。您可以在控制器代碼做到這一點:的

return View(myModel); 

代替

return View(); // without the model! 

其中yourmodel是typeof運算MyApp.Models.MyModel。只需啓動並傳遞它。

public ActionResult YourAction() 
{ 
    var myModel = new MyApp.Models.MyModel(); 
    // do other actions or put more data inside myModel 
    return View(myModel); 
} 
+0

當然,這更有意義。謝謝! – theog