Based on my research, the correct way to code a checkbox in MVC is as follows.
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
This will render a checkbox, render a label for the checkbox, and make the label clickable, which means clicking the label also toggles the checkbox.
But what about the case where there are multiple checkboxes for a single view-model field? (For example, maybe each checkbox represents a bit within an integer value.) Or, better yet, what about radio buttons, where there are always several options associated with the same field?
In these cases, there seems to be issues with the code above. Either not all elements would be associated with the same field, or multiple elements with the same ID would be rendered.
I have been researching this for a while now. I have found many solutions; however, they all seem to either not have a clickable label, or they require a bunch of custom and/or non-standard coding. Some avoid the use of RadioButtonFor/LabelFor completely, choosing instead to code the raw HTML.
Coding the raw HTML is fine, but didn't the designers of MVC not anticipate that we may need multiple radio buttons for the same field? And, if they did, how did they intended it to be coded?
EDIT:
After researching this some more, the code below is the best way I've found to code radio buttons. This code assumes I've defined an enum for each of my radio options.
@Html.RadioButtonFor(m => m.Gender, Gender.Male, new { id = "gender-male" })
@Html.LabelFor(m => m.Gender, Gender.Male.ToString(), new { @for = "gender-male" })
@Html.RadioButtonFor(m => m.Gender, Gender.Female, new { id = "gender-female" })
@Html.LabelFor(m => m.Gender, Gender.Female.ToString(), new { @for = "gender-female" })
Maybe this is the best I can expect, but it still troubles me a little.
Why is so much customization for basic stuff such as IDs required? Again, didn't Microsoft anticipate that we'd want multiple radio buttons associated with the same field?
if the enum name isn't the same as the description I want for the radio button label, this approach doesn't seem to support field attributes such as
[Display(Name = "")]
.
(I guess the correct handling of multiple checkboxes will be deferred to another question.)
RadioButtonFor
should have overloads likeDropDownListFor
where I can pass a list of items and radio buttons for each item would be generated with clickable labels. – Rickey