通过复选框传递布尔值

时间:2016-08-24 09:12:35

标签: html asp.net-mvc asp.net-mvc-4 razor checkbox

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

这是我的财产

  public bool MyBooleanValue{ get; set; } = true;

和这里;我的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" />

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

1 个答案:

答案 0 :(得分:4)

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

@Html.LabelFor(x => x.MyBooleanValue)
@Html.CheckBoxFor(x => x.MyBooleanValue)

如果 MyBooleanValue true false ,则可以检查 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">

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

相关问题