我刚刚注意到Html.CheckBox(“foo”)生成2个输入而不是一个,有人知道为什么是这样吗?

<input id="foo" name="foo" type="checkbox" value="true" />
<input name="foo" type="hidden" value="false" /> 

当前回答

使用Contains,它将与两个可能的post值一起工作:"false"或"true,false"。

bool isChecked = Request.Form["foo"].Contains("true");

其他回答

使用Contains,它将与两个可能的post值一起工作:"false"或"true,false"。

bool isChecked = Request.Form["foo"].Contains("true");

手动方法是这样的:

bool IsDefault = (Request.Form["IsDefault"] != "false");

在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);
}

当复选框被选中并提交时,执行此操作

if ($('[name="foo"]:checked').length > 0)
    $('[name="foo"]:hidden').val(true);

请参考

你可以尝试像这样初始化Model的构造函数:

public MemberFormModel() {
    foo = true;
}

在您看来:

@html.Checkbox(...)
@html.Hidden(...)