我刚刚注意到Html.CheckBox(“foo”)生成2个输入而不是一个,有人知道为什么是这样吗?
<input id="foo" name="foo" type="checkbox" value="true" />
<input name="foo" type="hidden" value="false" />
我刚刚注意到Html.CheckBox(“foo”)生成2个输入而不是一个,有人知道为什么是这样吗?
<input id="foo" name="foo" type="checkbox" value="true" />
<input name="foo" type="hidden" value="false" />
当前回答
你可以写一个helper来防止添加隐藏输入:
using System.Web.Mvc;
using System.Web.Mvc.Html;
public static class HelperUI
{
public static MvcHtmlString CheckBoxSimple(this HtmlHelper htmlHelper, string name, object htmlAttributes)
{
string checkBoxWithHidden = htmlHelper.CheckBox(name, htmlAttributes).ToHtmlString().Trim();
string pureCheckBox = checkBoxWithHidden.Substring(0, checkBoxWithHidden.IndexOf("<input", 1));
return new MvcHtmlString(pureCheckBox);
}
}
使用它:
@Html.CheckBoxSimple("foo", new {value = bar.Id})
其他回答
当我使用WebGrid时,我发现这确实引起了问题。WebGrid上的排序链接将由加倍的查询字符串或x=true&x=false转换为x=true,false,并在复选框中导致解析错误。
我最终使用jQuery在客户端删除隐藏字段:
<script type="text/javascript">
$(function () {
// delete extra hidden fields created by checkboxes as the grid links mess this up by doubling the querystring parameters
$("input[type='hidden'][name='x']").remove();
});
</script>
当复选框被选中并提交时,执行此操作
if ($('[name="foo"]:checked').length > 0)
$('[name="foo"]:hidden').val(true);
请参考
手动方法是这样的:
bool IsDefault = (Request.Form["IsDefault"] != "false");
这是Alexander Trofimov解决方案的强类型版本:
using System.Web.Mvc;
using System.Web.Mvc.Html;
public static class HelperUI
{
public static MvcHtmlString CheckBoxSimpleFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, object htmlAttributes)
{
string checkBoxWithHidden = htmlHelper.CheckBoxFor(expression, htmlAttributes).ToHtmlString().Trim();
string pureCheckBox = checkBoxWithHidden.Substring(0, checkBoxWithHidden.IndexOf("<input", 1));
return new MvcHtmlString(pureCheckBox);
}
}
如果未选中复选框,则不提交表单字段。这就是为什么隐藏字段中总是有假值的原因。如果你不选中复选框,表单仍然会有隐藏字段的值。这就是ASP。NET MVC处理复选框值。
如果您想确认这一点,请在表单上放置一个复选框,而不是Html。隐藏,但带有<input type="checkbox" name="MyTestCheckboxValue"></input>。不选中复选框,提交表单并查看服务器端发布的请求值。您将看到没有复选框值。如果你有隐藏字段,它将包含MyTestCheckboxValue项的假值。