What am I misunderstanding about how Html.TextBoxFor works

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You need to clear your model state so your code would look something like:

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

Method 2

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)

Method 3

This should work for the first two:

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x