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"> 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?
@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:
checkbox
remains unchecked, the form submits only the hidden
value (false)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.