Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean with html helper Hidden and HiddenFor

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?

like image 481
Martin Avatar asked Mar 08 '10 09:03

Martin


People also ask

What does HTML HiddenFor do?

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.

Which HTML helper method should generate hidden field?

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.

How do you get the hidden field value in razor view?

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: $.

How do you set a hidden field value in a controller?

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.


2 Answers

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" />
like image 171
garik Avatar answered Sep 30 '22 23:09

garik


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.

like image 20
Paul Carroll Avatar answered Sep 30 '22 23:09

Paul Carroll