Search code examples
asp.net-mvcform-helpers

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:                 }

Solution

  • 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>
                    }