Proper usage of .net MVC Html.CheckBoxFor

sagesky36 picture sagesky36 · Oct 1, 2012 · Viewed 330.8k times · Source

All I want to know is the proper syntax for the Html.CheckBoxFor HTML helper in ASP.NET MVC.

What I'm trying to accomplish is for the check-box to be initially checked with an ID value so I can reference it in the Controller to see if it's still checked or not.

Would below be the proper syntax?

@foreach (var item in Model.Templates) 
{ 
    <td> 
        @Html.CheckBoxFor(model => true, item.TemplateId) 
        @Html.LabelFor(model => item.TemplateName)
    </td> 
}

Answer

Robert Koritnik picture Robert Koritnik · Oct 1, 2012

That isn't the proper syntax

The first parameter is not checkbox value but rather view model binding for the checkbox hence:

@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });

The first parameter must identify a boolean property within your model (it's an Expression not an anonymous method returning a value) and second property defines any additional HTML element attributes. I'm not 100% sure that the above attribute will initially check your checkbox, but you can try. But beware. Even though it may work you may have issues later on, when loading a valid model data and that particular property is set to false.

The correct way

Although my proper suggestion would be to provide initialized model to your view with that particular boolean property initialized to true.

Property types

As per Asp.net MVC HtmlHelper extension methods and inner working, checkboxes need to bind to boolean values and not integers what seems that you'd like to do. In that case a hidden field could store the id.

Other helpers

There are of course other helper methods that you can use to get greater flexibility about checkbox values and behaviour:

@Html.CheckBox("templateId", new { value = item.TemplateID, @checked = true });

Note: checked is an HTML element boolean property and not a value attribute which means that you can assign any value to it. The correct HTML syntax doesn't include any assignments, but there's no way of providing an anonymous C# object with undefined property that would render as an HTML element property.