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

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

当前回答

从ASP开始。NET (Core) 5,添加到你的启动:

services.Configure<MvcViewOptions>(options =>
{
    // Disable hidden checkboxes
    options.HtmlHelperOptions.CheckBoxHiddenInputRenderMode = CheckBoxHiddenInputRenderMode.None;
});

以你的观点为例:

<input class="form-check-input" asp-for="@Model.YourBool" />

此属性的附加隐藏字段不再在表单中创建:

<input class="form-check-input" type="checkbox" data-val="true" data-val-required="The YourBool field is required." id="YourBool" name="YourBool" value="true" />

来源:https://github.com/dotnet/aspnetcore/pull/13014 # issuecomment - 674449674

其他回答

手动方法是这样的:

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

当我使用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>

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

在。net core 6中,我遇到了同样的问题,我尝试了@Kolazomai答案,它是有效的。

using Microsoft.AspNetCore.Mvc;

builder.Services.Configure<MvcViewOptions>(
opt=>opt.HtmlHelperOptions.CheckBoxHiddenInputRenderMode = Microsoft.AspNetCore.Mvc.Rendering.CheckBoxHiddenInputRenderMode.None
);