2016-08-24 109 views
1

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

这里是我的财产

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. 我总是得到相同的值

+0

只要使用'@ Html.CheckBoxFor(m => m.MyBooleanValue)' –

回答

3

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

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

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


另外也可以使用简单的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不包含此值。