我对Html.TextBoxFor如何工作有什么误解?

时间:2010-02-19 16:03:11

标签: asp.net asp.net-mvc

我只是想尝试使用新版本重新进入.NET MVC,我无法理解视图是否绑定到DataModel。

我有一个带有属性“first_name”的模型,在HTML表单中我有以下

<%= Html.TextBox("first_name", Model.first_name)%>
<%= Html.TextBoxFor(model => model.first_name) %> 
<input type="text" name="first_name" id="first_name" class="myLabel" 
       value="<%=Model.first_name %>" />

如果我在模型上设置first_name属性并执行

,则在控制器上的操作中
mymodelObject.first_name = "Test";
return View(mymodelObject);

只有第三个文本框获取此first_name值而另外两个不匹配的原因是什么?

编辑:

我可能还没有解释得这么好,对不起。想象一下,我有2个控制器方法 -

public ActionResult Register()
{
    Registration model = new Registration();
    model.first_name = "test";
    return View(model);
}

使用这个任何一个绑定都可以。

显示之后,我单击表单上的一个按钮,然后尝试运行:

[HttpPost]
public ActionResult Register(Registration_ViewData model)
{
    model.first_name = "Steve";
    return View(model);
}

我问的是为什么第3个而不是前2个将“Steve”绑定为新名称。

3 个答案:

答案 0 :(得分:8)

您需要清除模型状态,以便您的代码看起来像:

[HttpPost]
public ActionResult Register(Registration model)
{
    ModelState.Clear();
    model.first_name = "Steve";
    return View(model);
}

答案 1 :(得分:5)

因为HTML帮助程序从ModelState读取值而不是从模型读取值。为了改变你的行为,你也需要使用ModelState (见:Changing model’s properties on postback

答案 2 :(得分:1)

这适用于前两个:

<%= Html.TextBox("first_name", x => x.first_name)%>
<%= Html.TextBoxFor(model => model.first_name) %>