使用APS.net MVC开发时候,页面上CheckBox控件在选中状态下,服务器端从View中得到的值是“true,false",而不是期望中的”true“。
试图解析作为bool值使用会触发FormatException,提示"true,false 不是 Boolean 的有效值。"
<label> @Html.CheckBox("x") </label>
使用<label style="float:left;" class="control-label">@Request.QueryString["x"]</label>
查询参数值发现没有选中时候值为“false”,选中时候值为“true,false”。
百思不得其解,遍寻度娘不见中文资料。不知道是没人遇到还是这个问题太基础了,大家都知道。无奈之下开启英文搜索模式,寻得一鳞半爪。记之。
ASP页面中的代码 <label> @Html.CheckBox("x") </label> 在浏览器客户端得到的html代码是
<input checked="checked" id="x" name="x" type="checkbox" value="true" /> <input name="x" type="hidden" value="false" />多出一个隐藏的checkbox。这是ASP MVC框架为了保持checkbox x未选中情况下post和get操作中仍然有参数x的值。
这样造成的问题可以通过参考资料1中的jQuery代码解决。
参考资料
【1】Jquery fix ASP.Net MVC checkbox “true,false” value
http://www.mindstorminteractive.com/topics/jquery-fix-asp-net-mvc-checkbox-truefalse-value/
【2】Why does CheckBox return "true, false" instead of "true"
http://forums.asp.net/t/1589746.aspx?Why+does+CheckBox+return+true+false+instead+of+true+
【3】Html.Checkbox does weird stuff
http://forums.asp.net/t/1425806.aspx