JQuery Mobile JQuery Mobile - 1 month ago 8
C# Question

Getting Checkbox Value in ASP.NET MVC 4

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
@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 not checked, form submit only hidden (false)
  • If checked, then form submit two fields (false and true) and MVC set true for bool property

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

This will always send default value, if checked