2014-09-18 47 views
0

我是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"
  • 別的東西嗎?
+0

自動綁定可能會創建一個MyViewModel但填充值?模型屬性可能爲null。 – Jasen 2014-09-18 18:14:04

+0

如果您詢問表單是否已過帳?將[HttpPost]屬性附加到您的方法中,即期望模型的方法。 – Rab 2014-09-18 18:15:04

回答

4

您應該對您的GET和POST請求使用不同的操作。不要試圖讓一種方法做太多。

[HttpGet] 
public ActionResult Index() 
{ 
    // handle the GET request 
} 

[HttpPost] 
public ActionResult Index(MyViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // it's a post and the data is valid 
    } 
} 

正確的方法,然後將取決於它是否是一個GET或POST

+0

好吧,我沒有意識到,如果我有兩種方法,我可以在Post one上返回'View()'並且它仍然直接指向'Index'。謝謝! – DLeh 2014-09-18 18:25:42

2

創建兩個動作,一個它接受一個模型實例,一種不被調用。

即使您「正在進入同一頁面」,您實際上正在執行兩種截然不同的操作。第一個動作加載一個初始頁面,第二個動作發佈一些值以執行操作。兩個操作意味着兩種方法:

[HttpGet] 
public ActionResult Index() 
{ 
    // perform any logic, but you probably just want to return the view 
    return View(); 
} 

[HttpPost] 
public ActionResult Index(MyViewModel model) 
{ 
    // respond to the model in some way 
    return View(model); 
    // or return something else? a redirect? it's up to you 
} 

請注意,這種類型打破了您寧靜的網址。考慮語義你在這些動作做什麼:

  • 查看索引
  • 發佈至索引

第一個是有道理的,但第二個可能沒有。通常當你POST東西你東西有關的某種模型或行動。 「索引」並不真正描述一項行動。你在「創造」什麼?你「編輯」 - 什麼?這聽起來像是POST動作中更有意義的動作名稱。