Adam
Adam

Reputation: 1715

Model value wrong in generated view

Ran into a very strange problem here using MVC3 and razor.

The app I'm putting together shows a series of interview questions. I have a view for a question (the content of the question comes from the viewmodel). So after I post back from one question it is possible I will be returning the same question view (but using a different viewmodel instance).

In the viewmodel I have a long property like so:

public long QuestionID { get; set; }

I was trying to use a hidden input field to store the value in the view:

@Html.HiddenFor(m => m.QuestionID)

My problem is that as I go from question to question the hidden field is not changing in the final generated html. It remains the value of the first questionID in all further questions. All the other content is changing just fine and I have a couple other hidden fields that are working fine. I have verified the correct values in the controller where the model is generated. I can set a breakpoint in the razor file and I can see the model is as it should be with the correct QuestionID. I tried using @Html.TextBoxFor as well and I have the same problem. When I manually make a hidden field like below it works fine, and this is what is really bothering me.

<input type="hidden" id="QuestionID" name="QuestionID" value="@Model.QuestionID" />

Any idea why this is happening?

Upvotes: 5

Views: 963

Answers (1)

bhamlin
bhamlin

Reputation: 5187

After a form post, MVC keeps track of the posted values in ModelState. Even if you change the values of your model, the HiddenFor helpers will use the ModelState value first. This is due to the fact that binding may have failed, or binding may be a complex object and the string value in ModelState is what they actually entered.

You can solve this by using

ModelState.Remove("QuestionID");

or, if you really just want to treat it as a completely new page,

ModelState.Clear();

Upvotes: 8

Related Questions