2012-04-23 84 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