Arif YILMAZ
Arif YILMAZ

Reputation: 5866

How to display checkboxes in MVC with Razor

I am trying to create a View with a ViewModel which includes many Checkboxes. I can list the checkboxes but I couldnt figure out the labels.

@for (int i = 0; i < Model.colors.Count; i++)
{
    @Html.EditorFor(x => x.colors[i].CHECKED)
    @Html.LabelFor(x => x.colors[i].COLOR)           
}

the second line in the loop displays "COLOR" next to every checkbox. What is the proper way to display the value in x.color[i].COLOR?

Upvotes: 0

Views: 905

Answers (1)

user3559349
user3559349

Reputation:

The first parameter of LabelFor() should be the same as used for EditorFor() so the the label is associated with the controls (clicking on the label toggles the checked state of the checkbox). A second parameter can be provided for the 'display text'. Refer documentation

@for (int i = 0; i < Model.colors.Count; i++)
{
    @Html.EditorFor(x => x.colors[i].CHECKED)
    @Html.LabelFor(x => x.colors[i].CHECKED, Model.colors[i].COLOR)     
}

Upvotes: 3

Related Questions