我刚刚注意到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" />
当前回答
这不是bug!它增加了在将表单提交到服务器后始终具有值的可能性。 如果你想用jQuery处理复选框输入字段,请使用prop方法(将'checked'属性作为参数传递)。 例子:$ (' # id ') .prop(检查)
其他回答
在2020/11和。net 5预览版中,有一个拉请求应该使这种行为可控。谢谢大家!
不管怎样,如果有人觉得它有用,.NET Core 3.0的Alexander Trofimov的回答:
public static IHtmlContent CheckBoxSimple(this IHtmlHelper htmlHelper, string name)
{
TextWriter writer = new StringWriter();
IHtmlContent html = htmlHelper.CheckBox(name);
html.WriteTo(writer, HtmlEncoder.Default);
string checkBoxWithHidden = writer.ToString();
string pureCheckBox = checkBoxWithHidden.Substring(0, checkBoxWithHidden.IndexOf("<input", 1));
return new HtmlString(pureCheckBox);
}
你可以写一个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})
这不是bug!它增加了在将表单提交到服务器后始终具有值的可能性。 如果你想用jQuery处理复选框输入字段,请使用prop方法(将'checked'属性作为参数传递)。 例子:$ (' # id ') .prop(检查)
你可以尝试像这样初始化Model的构造函数:
public MemberFormModel() {
foo = true;
}
在您看来:
@html.Checkbox(...)
@html.Hidden(...)
这是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);
}
}