What's up with this? The viewmodel variable is a bool with value true.
<%= Html.HiddenFor(m => m.TheBool) %>
<%= Html.Hidden("IsTimeExpanded",Model.TheBool) %>
<input type="hidden" value="<%=Model.TheBool%>" name="TheBool" id="TheBool">
Results in:
<input id="TheBool" name="TheBool" value="False" type="hidden">
<input id="TheBool" name="TheBool" value="False" type="hidden">
<input value="True" name="TheBool" id="TheBool" type="hidden">
What am I doing wrong? Why don't the helpers work as intended?
Html. HiddenFor<TModel, TProperty> extension method is a strongly typed extension method generates a hidden input element for the model property specified using a lambda expression.
Hidden() is a basic typed helper method or loosely typed helper method, that isn't bounded with any model. It contains 2 parameters; Hidden Field Name and Hidden Field Value.
You can still employ input type="hidden" , but initialize it with a value from the ViewData or for Razor, ViewBag . Then you can pass data between the client and server via ajax. For example, using jQuery: $.
The Controller consists of two Action methods. Inside this Action method, the value of the Name is set in a ViewBag object which will be later set in the Hidden Field created using Html. Hidden helper function. Inside this Action method, the value of the Hidden Field created using the Html.
1) use different (unique) ids
2) don't use this helper, use
<input type="hidden" name="the-name"
value="<%= Html.AttributeEncode(Model.TheBool) %>" id="TheBool_1216786" />
As answered here the problem is that HTML helpers by default use the posted values (if available) then refer to the model. Personally I don't think this makes a whole bunch of sense and now wonder how many other bugs lie in wait throughout our platform.
Anyway, the solution posted in the aforementioned answer will solve the problem, just add this line before you return from the controller:
ModelState.Remove("TheBool")
And yes, it's a bit rubbish because you can only use a string reference... but it does work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With