什么是我误解有关如何Html.TextBoxFor作品 [英] What am I misunderstanding about how Html.TextBoxFor works
问题描述
我只是试图重新进入.NET MVC的新版本,我不能让我的头一轮的方式可以查看绑定到数据模型。
I'm just trying to get back into .NET MVC with the new release and I can't get my head round the way may view is binding to the DataModel.
我有一个属性FIRST_NAME和HTML表单我有以下范围内的模型
I have a model with a property "first_name" and within an HTML form I have the following
<%= 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财产并做
In an action on a controller if I set the first_name property on my model and do
mymodelObject.first_name = "Test";
return View(mymodelObject);
什么是只有第三个文本框在这个FIRST_NAME值回升,另外两个没有什么原因呢?
What is the reason only the third textbox picks up on this first_name value and the other two don't?
编辑:
我可能没有解释这个不够好,对不起。想象一下,我有2个控制器方法 -
I probably haven't explained this well enough, sorry. Imagine I have 2 controller methods -
public ActionResult Register()
{
Registration model = new Registration();
model.first_name = "test";
return View(model);
}
通过这一个或者绑定的工作。
With this one either binding works.
在此已经显示我,然后单击窗体上的一个按钮,并尝试并运行此:
After this has been displayed I then click a button on the form and try and run this:
[HttpPost]
public ActionResult Register(Registration_ViewData model)
{
model.first_name = "Steve";
return View(model);
}
什么我问的是为什么第三,但不是第2绑定到史蒂夫作为新名称。
What I'm asking is why does the 3rd but not the first 2 bind to "Steve" as the new name.
推荐答案
由于HTML助手宣读了ModelState中,而不是从模型的价值。为了这种行为,你需要用的ModelState工作以及变化。结果
(参见:<一href=\"http://stackoverflow.com/questions/707569/asp-net-mvc-changing-models-properties-on-postback\">Changing模型对回传属性)
Because HTML helpers read the value from the ModelState and not from the model. In order the change that behavior you'll need to work with the ModelState as well.
(see: Changing model’s properties on postback)
这篇关于什么是我误解有关如何Html.TextBoxFor作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!