user1618825
user1618825

Reputation:

Html.LabelFor is always displaying property name instead of value

In my MVC4 project, I am showing Checkbox and its corresponding Label so that when the label is clicked the corresponding checkbox will be checked. But when i use the @Html.LabelFor it is displaying property name instead of showing its value. Also when i click the label the corresponding checkbox is not getting checked. What's wrong here ?

@for (int i = 0; i < Model.AddOns.Count; i++)
{
    @Html.CheckBoxFor(m => m.AddOns[i].IsActive)
    @Html.LabelFor(m => m.AddOns[i].Name)
    @Html.HiddenFor(m => m.AddOns[i].Id)
}

When i use DisplayFor it is showing value but not checkbox getting checked on clicking the label.

Upvotes: 5

Views: 5893

Answers (1)

Simon C
Simon C

Reputation: 9508

You want the label to relate to the checkbox for IsActive, but the label to read the Name. So the LabelFor should refer to the IsActive property, and the label string just gets passed in as a second param.

I think you want this:

@for (int i = 0; i < Model.AddOns.Count; i++)
{
    @Html.CheckBoxFor(m => m.AddOns[i].IsActive)
    @Html.LabelFor(m => m.AddOns[i].IsActive, Model.AddOns[i].Name)
    @Html.HiddenFor(m => m.AddOns[i].Id)
}

Upvotes: 5

Related Questions