开发者

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 d开发者_运维百科oing wrong? Why don't the helpers work as intended?


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.


Here's an example in razor:

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

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

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


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)
  }          
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜