开发者

Html.CheckBox renders two checkboxes

开发者 https://www.devze.com 2023-02-21 02:33 出处:网络
When I try to seriali开发者_开发百科ze <%: Html.CheckBox(\"Something\", true) %> in jquery (using form.serialize()) I get two checkboxes, one says true, and the other false.I am aware that MVC r

When I try to seriali开发者_开发百科ze <%: Html.CheckBox("Something", true) %> in jquery (using form.serialize()) I get two checkboxes, one says true, and the other false. I am aware that MVC renders true, false for checkboxes that are true, so if I wasn't coming through javascript, I'd just check for the presence of true, but how do I know if my checkbox is checked after doing form.serialize?


If you look at the output HTML - you'll see that the Html.Checkbox() actually renders an additional hidden input in there with the same name. That's why you're seeing two values. I believe MS decided to do this so that a proper bool gets POSTed (rather than a string value of 'on' for checkboxes).

To get around this, I never use Html.Checkbox() helper anymore, I always just write the full HTML myself.


Why not simply:

var isChecked = $('#idofyourcheckbox').is(':checked');

As far as the values stored in the form.serialize() string are concerned they are destined to go to the server where you can simply work with boolean properties.

0

精彩评论

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