简体   繁体   中英

Getting Checkbox Value in ASP.NET MVC Action

I'm working on an ASP.NET MVC app. The model for my form looks like the following:

public class ViewModel
{
    public bool IsActive { get; set; }
}

In my form, I have the following HTML.

<label class="checkbox pull-left">
   <input type="checkbox" id="IsActive" name="IsActive" data-val="true" data-val-required="The IsActive field is required.">
   <i></i>Active/Deactive
   <input name="IsActive" type="hidden">
</label>

When I post the form, the IsActive value in the model is always false. However, the Name property in the model has a value. I've tested this by setting a breakpoint in the following:

[HttpPost]
public ActionResult MyAction(ViewModel model)
{
    // model.IsActive always is false
}

Why isn't the Checkbox value getting set?

What should I do to fix this?

You are not setting the value attribute in either the checkbox or its associated hidden input so no value is posted and the value of your property is its default value ( false ). It needs to be

<label class="checkbox pull-left">
    <input type="checkbox" id="IsActive" name="IsActive" value="true" ....>
    <i></i>Active/Deactive
    <input name="IsActive" type="hidden" value="false">
</label>

Side note: Is there any reason you're not using @Html.CheckBoxFor(m => m.IsActive) to generate the correct html?

You have to set value attr of the check box to fetch the value .

data-val is different and not used as value attr in either HTML or MVC

我建议你使用razor和@Html.CheckBoxFor(m => m.IsActive)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM