views:

29

answers:

2

Hi,

I create a strongly typed form like this in my controller:

return View("BlaForm", Bla);

In the view I use something like this:

(1)

<%= Model.Version %>

(2)

<%= Html.Hidden("Version", Model.Version)%>

Here (1) is just for debugging purposes.

After a successive update of my object this produces something like this:

(1)

10

(2)

<input id="Version" name="Version" type="hidden" value="9" />

The hidden value is out of synch for some strange reason ???!!! The Version value was definitely 10 in this case as established by the debugger. Why is this? Are hidden value somehow cached?

Thanks.

Christian

PS:

I also do:

if (TempData["ViewData"] != null)
{
 ViewData = TempData["ViewData"] as ViewDataDictionary;
}

in the controller action to maintain form values in case validation errors happen. This seems to be the reason. But still I explicitely do: <%= Html.Hidden("Version", Model.Version)%> .... ???? Maybe I missunderstand the lif cycle a bit?

A: 

Html helper will always use the value in the GET or POST request before the value in your model or ViewData. This means that if you post Version=9 to a controller action and inside this action you try to modify its value to 10, when you return the View, the Html.Hidden helper will use the POSTed value and not the one in your Model. The only workaround is a custom HTML helper or simply:

<input id="Version" name="Version" type="hidden" value="<%= Model.Version %>" />
Darin Dimitrov
A: 

HTML helper will always look for values in ModelStateDictionary, then in ViewData and after this use the value parameter given into helper method.

The 2 other places are in your case.

ModelState state = this.ViewData.ModelState["Version"]; 
state.Value; // this is the value out of the ModelStateDictionary

object value = this.ViewData["Version"]; // this is the value if set 
// out of the ViewData Collection

The ModelStateDictionary gets its entries, while model binding. If you have the Version as a action method parameter, the Modelbinder (in your case the DefaultModelBinder) will enter the key version with the supplied value of get or post request.

If you change the value, put it in your model, you have to update the ModelStateDictionary too.

Christian13467