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.
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 %>" />
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);
What is the reason only the third textbox picks up on this first_name value and the other two don’t?
Edit:
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);
}
What I’m asking is why does the 3rd but not the first 2 bind to “Steve” as the new name.
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)