通过复选框传递布尔值

Cie*_*eja 1 html checkbox asp.net-mvc razor asp.net-mvc-4

我想通过复选框传递我的布尔值。

这是我的财产

  public bool MyBooleanValue{ get; set; } = true;
Run Code Online (Sandbox Code Playgroud)

这里是我的 HTML:

<input type="checkbox" id="@nameof(Model.MyBooleanValue)" name="my-boolean" value="1" class="" checked="checked" />

<label for="@nameof(Model.MyBooleanValue)">some text</label>

<input type="hidden" name="my-boolean" value="true" />
Run Code Online (Sandbox Code Playgroud)

默认情况下,我想检查字段。这段代码有什么问题?我使用 ASP.NET MVC 5。我总是得到相同的值

Kry*_*zal 6

最简单的方法是使用 MVC 助手:

@Html.LabelFor(x => x.MyBooleanValue)
@Html.CheckBoxFor(x => x.MyBooleanValue)
Run Code Online (Sandbox Code Playgroud)

如果MyBooleanValuetruefalse,您可以检查FormCollection,具体取决于复选框状态。


或者使用简单的 html 代码:

<label for="MyBooleanValue">Some label text</label>
<input type="checkbox" id="MyBooleanValue" name="MyBooleanValue" checked="checked" value="Some value you want to pass if checked">
Run Code Online (Sandbox Code Playgroud)

如果选中该复选框,则该将在表单中传递。否则,FormCollection不包含此值。