sagesky36
sagesky36

Reputation: 4692

Html.LabelFor statement not displaying as assigned value

I'm displaying a GuarantorName inside a foreach statement via an Html.LabelFor helper.

However, I'm not getting the expected result.

Instead of displaying the actual value of the GuarantorName, it's simply printing like this: The Label value says the actual field name which is : GuarantorName, whereas I need the actual value of the name for that field (like "Bill Yeager") which I have verified during debugging has various different first names.

During debugging, I can see in my list that I have actual first names in the collection.

How can I accomplish this?

Here is my view in the Code:

@foreach (var item in Model.Guarantors)
                {
                    <td>
                        @Html.CheckBoxFor(model => item.isChecked)
                        @Html.LabelFor(model => item.GuarantorName)
                    </td>
                }

If I try this, I get the following error :

@Html.DisplayFor(model => item.GuarantorFirstName + item.GuarantorLastName)

Exception Details: System.InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Source Error:


Line 95:                     <td>
Line 96:                         @Html.CheckBoxFor(model => item.isChecked)
Line 97:                         @Html.DisplayFor(model => item.GuarantorFirstName + item.GuarantorLastName)
Line 98:                     </td>
Line 99:                 }

Upvotes: 4

Views: 12934

Answers (2)

kavitha Reddy
kavitha Reddy

Reputation: 3333

@foreach (var item in Model.Guarantors)
                {
                    <td>
                        @Html.CheckBoxFor(model => item.isChecked)
                        @Html.DisplayFor(model => item.GuarantorName)
                    </td>
                }


And also we can use when used IList<Model>

@for(int i=0;i<model.Guarantors.count();i++)
{
 <td>
                        @Html.CheckBoxFor(model =>model[i].isChecked)
                        @Html.DisplayFor(model => model[i].GuarantorName)
                    </td>
}

Upvotes: 0

Forty-Two
Forty-Two

Reputation: 7605

LabelFor displays the property name. You want DisplayFor to show the value of the field.

@foreach (var item in Model.Guarantors)
                {
                    <td>
                        @Html.CheckBoxFor(model => item.isChecked)
                        @Html.DisplayFor(model => item.GuarantorName)
                    </td>
                }

Upvotes: 22

Related Questions