2012-04-23 82 views
0

SomeModel定義爲:該模型如何在HttpPost上填充?

public class SomeModel 
{ 
    public string property1 { get; set } 
    public bool property2 { get; set; } 
} 

我有一個動作:

public ActionResult Edit(int id) 
{ 
    SomeModel model = new SomeModel(); 
    //... populate model ... 
    return View(model); 
} 

假設在視圖property1property2被實例化爲@Html.EditorFor,在這種情況下property1將被呈現爲<input type='text'>property2將是<input type='checkbox'>

如果我有以下控制器動作,以處理從編輯表單提交:

[HttpPost] 
public ActionResult Edit(int id, SomeModel model, FormCollection collection) 
{ 
} 

怎樣的參數模型得到填充,如果有的話?

+0

看看收集鑰匙,MVC使用這些按鍵的名稱,試圖映射到模型。有時,如果遇到麻煩,你可以使用綁定屬性 – Manatherin 2012-04-23 10:19:48

+0

手動指定前綴,我認爲在你的編輯方法中,你只需要添加模型作爲參數。模型聯編程序將檢查您的所有 html標籤以及它們的「名稱」和「標識」屬性,並將它們映射到實體。也不知道命名您的「編輯」方法「行動」。 – 2012-04-23 11:35:12

+0

@Alex,我糾正了錯誤。方法名稱應該是Edit。 – 2012-04-23 12:00:25

回答

2

如果你使用類似

[HttpPost] 
public ActionResult Action(SomeModel model) 
{ 
    //do something 
} 

所有模型綁定的,你會被照顧的,如果你在你的視圖中使用的標準Html.EditorFor語法,因爲你已經提到。

@Html.EditorFor(model => model.Property1) 
@Html.EditorFor(model => model.Property2) 

更多關於模型綁定here