我只是想尝试使用新版本重新进入.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 %>" />
Run Code Online (Sandbox Code Playgroud)
在控制器上的操作中,如果我在模型上设置first_name属性并执行此操作
mymodelObject.first_name = "Test";
return View(mymodelObject);
Run Code Online (Sandbox Code Playgroud)
是什么原因只有第三个文本框获取此first_name值而另外两个没有?
编辑:
对不起,我可能还没有解释得这么好.想象一下,我有2个控制器方法 -
public ActionResult Register()
{
Registration model = new Registration();
model.first_name = "test";
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
有了这个,任何一个绑定工作.
在显示之后,我单击表单上的一个按钮,然后尝试运行:
[HttpPost]
public ActionResult Register(Registration_ViewData model)
{
model.first_name = "Steve";
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
我问的是为什么第3个而不是第2个以"Steve"作为新名称.
您需要清除模型状态,以便您的代码看起来像:
[HttpPost]
public ActionResult Register(Registration model)
{
ModelState.Clear();
model.first_name = "Steve";
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
因为HTML帮助程序从ModelState读取值而不是从模型读取值.为了改变行为,您还需要使用ModelState.
(请参阅:在回发时更改模型的属性)
| 归档时间: |
|
| 查看次数: |
9624 次 |
| 最近记录: |