Html.LabelFor always displays property name instead of value

In my MVC4 project, I show the Checkbox and its corresponding Label so that when I click the label, the corresponding checkbox is checked. But when I use @Html.LabelFor , it displays the property name instead of showing its value. Also, when I click the label, the corresponding checkbox is not checked. What is 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 shows the value but the checkbox is not checked by clicking the label.

+4
source share
1 answer

You want the label to refer to the IsActive box for IsActive , but the label to read Name . Thus, LabelFor must reference the IsActive property, and the label string is simply passed as the second parameter.

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) } 
+4
source

Source: https://habr.com/ru/post/1487993/


All Articles