Getting Checkbox Value in ASP.NET MVC 4

JQuery Mobile picture JQuery Mobile · Feb 6, 2013 · Viewed 294.7k times · Source

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

public class MyModel
{
    public string Name { get; set; }
    public bool Remember { get; set; }
}

In my form, I have the following HTML.

<input id="Name" name="Name" type="text" value="@Model.Name" />
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
<label for="Remember">&nbsp;Remember Me?</label>

When I post the form, the Remember 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(MyModel model)
{
  Console.WriteLine(model.Remember.ToString());
}

I can't figure it out. Why isn't the Checkbox value getting set?

Answer

webdeveloper picture webdeveloper · Feb 6, 2013
@Html.EditorFor(x => x.Remember)

Will generate:

<input id="Remember" type="checkbox" value="true" name="Remember" />
<input type="hidden" value="false" name="Remember" />

How does it work:

  • If checkbox remains unchecked, the form submits only the hidden value (false)
  • If checked, then the form submits two fields (false and true) and MVC sets true for the model's bool property

<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />

This will always send the default value, if checked.