我是MVC的新手,所以我試圖找出一些最佳實踐。MVC檢測模型爲空
假設我有一個控制器HomeController
方法Index(MyViewModel model)
:
public ActionResult Index(MyViewModel model)
{
//if loading the page for the first time, do nothing
//if the page has been posted data from somewhere, then I want to use
// some of the arguments in model to load other data, like say search results
}
當我瀏覽到/Index
頁,我(我自己)預期model
對象爲空來通過,但事實並非如此。 MVC(莫名其妙)爲我創建了一個MyViewModel
。
我的問題是,確定model
是自動創建還是通過文章創建的最佳方式或最一致的方法是什麼?
思路:
- 創建於
MyViewModel
屬性時設置視圖時回發 - 檢查,如果
Request.HttpMethod == "GET"
或"POST"
- 別的東西嗎?
自動綁定可能會創建一個MyViewModel但填充值?模型屬性可能爲null。 – Jasen 2014-09-18 18:14:04
如果您詢問表單是否已過帳?將[HttpPost]屬性附加到您的方法中,即期望模型的方法。 – Rab 2014-09-18 18:15:04