2

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?

3 Answers 3

5

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

I suggest you to use razor and @Html.CheckBoxFor(m => m.IsActive).

1 Comment

It is usually better to elaborate on the answer in first attempt itself or the OP would ask you for the same later...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.