ASP.NET MVC Hidden Form Field Bug

So, you have an MVC form and you’re using the following:

<%= Html.Hidden(“Command”, Model.Command) %>

or

<%= Html.HiddenFor(m => m.Command) %>

You are doing postbacks to the form, and you’re changing the value of Command in the controller, but for some reason, the value being stored in the hidden field is the old value, not the changed value from said controller.  I have been pulling my hair out trying to figure out why.  I finally found the answer on stackoverflow.com.

http://stackoverflow.com/questions/594600/possible-bug-in-asp-net-mvc-with-form-values-being-replaced

It turns out this is by design, even though Haacked himself doesn’t necessarily like it.  The reason is that the helper methods will pull the values from the model state, not from your passed model.  This is the correct behavior when dealing with textboxes and other user-changeable fields, but it seems wrong to do this with hidden fields, and Phil sort of agrees in the post above.  It would be a breaking change, so I doubt it will ever be “corrected”.  You need to build up your own hidden field instead, as shown below and in the post above.

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

Comments (1) -

steve
steve
1/17/2012 9:29:57 AM #

thanks for this

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

John West

John West is an independent technology consultant who specializes in using technology to improve business processes.  That means that technology for its own sake isn't worth much; it's value only comes from helping people do things better, cheaper and faster.

That said, he spends way too much time testing cutting-edge gadgets that often come with promises of making things better and faster, but often fail to live up to those promises.  And they usually fail on the cheaper front as well.

Month List

Page List