I’m trying to implement what this answer suggests but without storing the display name in my model code, so I believe it’s a separate question.
I have an MVC view
<%@ Page Language="C#" MasterPageFile="PathToMaster" Inherits="System.Web.Mvc.ViewPage<ModelData>" %>
and a model:
public class ModelData {
public bool Option1 { get; set; }
}
and I have a .aspx with HTML markup for a form that contains a checkbox:
<label for="MyCheckbox">Your choice</label>
<%= Html.CheckBoxFor(Model=>Model.Option1, new { id="Option1", @class="checkbox", onchange="return myValidation();", name="MyCheckbox", value="Option one" } ) %>
which when it is compiled yields this HTML:
<label for="MyCheckbox">Your choice</label>
<input class="checkbox" id="Option1" name="Option1" onchange="return myValidation();" type="checkbox" value="Option one" /><input name="Option1" type="hidden" value="false" />
and whenever I check the checkbox and submit the form the controller-action
class MyController : Controller {
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult RequestStuff( ModelData data )
{
}
}
receives data where Option1 is false.
What am I doing wrong? How do I make the checkbox map to the model member?
Since you said changing the alias in the helper expression didn’t cut it, I took the time to prepare the MVC2 test project, here’s how it looks:
MyModel.cs:
Controller’s actions:
The view (MyAction.aspx):
Looks like this:
And the result after checking the checkbox:

By the way, the View was generated entirely (well, almost entirely, I changed
TextBoxFortoCheckBoxFor) by Add View -> Strongly Typed View for the MyModel class and template: Edit.So it looks like the binding above should be OK. Try this and then you can fiddle with custom options on checkboxes. 🙂
Like I wrote in the other answer, the idea is essentially the same, only in MVC3 the Razor syntax looks a bit cleaner. But that’s about it when it comes to differences. 🙂