Possible bug in ASP.NET MVC with form values being replaced

Yes, this behavior is currently by design. Even though you’re explicitly setting values, if you post back to the same URL, we look in model state and use the value there. In general, this allows us to display the value you submitted on postback, rather than the original value.

There are two possible solutions:

Solution 1

Use unique names for each of the fields. Note that by default we use the name you specify as the id of the HTML element. It’s invalid HTML to have multiple elements have the same id. So using unique names is good practice.

Solution 2

Do not use the Hidden helper. It seems like you really don’t need it. Instead, you could do this:

<input type="hidden" name="the-name" 
  value="<%= Html.AttributeEncode(Model.Value) %>" />

Of course, as I think about this more, changing the value based on a postback makes sense for Textboxes, but makes less sense for hidden inputs. We can’t change this for v1.0, but I’ll consider it for v2. But we need to think through carefully the implications of such a change.

Leave a Comment