我只是想用新版本回到 .NET MVC,但我无法理解可能 View 绑定(bind)到 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 属性并执行,则在 Controller 上的操作中
mymodelObject.first_name = "Test";
return View(mymodelObject);
只有第三个文本框选择了这个 first_name 值而其他两个没有的原因是什么?
编辑:
我可能解释得不够清楚,抱歉。想象一下,我有 2 个 Controller 方法 -
public ActionResult Register()
{
Registration model = new Registration();
model.first_name = "test";
return View(model);
}
有了这个,任一绑定(bind)都有效。
显示后,我单击表单上的按钮并尝试运行:
[HttpPost]
public ActionResult Register(Registration_ViewData model)
{
model.first_name = "Steve";
return View(model);
}
我要问的是为什么第三个而不是前两个绑定(bind)到“史蒂夫”作为新名称。
最佳答案
您需要清除模型状态,以便您的代码如下所示:
[HttpPost]
public ActionResult Register(Registration model)
{
ModelState.Clear();
model.first_name = "Steve";
return View(model);
}
关于asp.net - 我对 Html.TextBoxFor 的工作原理有什么误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2297670/