Martin
Martin

Reputation: 2971

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?

Upvotes: 17

Views: 20461

Answers (4)

live-love
live-love

Reputation: 52366

Here's an example in razor:

html:
@Html.HiddenFor(Model => Model.TheBool, new { @id = "hdnBool" })

javascript:
alert($('#hdnBool').val());

model:
public class MyModel()
{
  public bool TheBool{ get; set; }
}

Upvotes: 0

AntDC
AntDC

Reputation: 1917

I had similar and ended up getting round it like this. The situation is the user wants a Save and then confirm save scenario....

I chose to use the solution below rather than

ModelSate.Remove("OperationConfirmed");

(which does work) as I feel it is more intuative....

@{
  string btnSaveCaption = "Save Changes";
  if (Model.OperationConfirmed)
  {
    btnSaveCaption = "Confirm Save Changes";
    @Html.Hidden("OperationConfirmed", true)
  }          
} 

Upvotes: 0

Paul Carroll
Paul Carroll

Reputation: 1887

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.

Upvotes: 3

garik
garik

Reputation: 5756

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" />

Upvotes: 15

Related Questions