1

I'm working on a view with IList<MyModel> model assigned and I'm stuck at displaying values with LabelFor (property name instead of its value is displayed), however, everything works fine with TextBoxFor even when it's used with the same property.

Part of the view code:

@model IList<MyModel>

  @for (var i = 0; i < Model.Count; i++)
    {
        <tr>
            <td>@Html.LabelFor(m => m[i].Code)</td>
            <td>@Html.TextBoxFor(m => m[i].Price)</td>
        </tr>
   }

Model class:

public class MyModel
  {
    public string Code { get; set; }

    public double Price { get; set; }
  }

@Html.TextBoxFor(m => m[i].Code) also works fine so the issue is apparently not related to the property itself.

I could use just Label(), but I need to POST the values from a form, so I also have to add a hidden field for Code and I feel it's not the most elegant solution.

Why TextBoxFor works, but LabelFor doesn't?

Łukasz Sypniewski
  • 602
  • 1
  • 10
  • 19

2 Answers2

4

LabelFor displays the name of the field (it's used to create a label for a control).

If you want to display the value of a field, use DisplayFor:

<tr>
    <td>@Html.DisplayFor(m => m[i].Code)</td>
    <td>@Html.TextBoxFor(m => m[i].Price)</td>
</tr>

Note: DisplayFor just displays a text value (like a label) which isn't included when the form is submitted. If you need the value to be returned with the form/model, then you need to add a hidden field. You can use @Html.HiddenFor(m => m[i].Code) which will create a hidden input rendered like <input type="hidden" name="myModels[0].Code" value="abc" />.

haldo
  • 14,512
  • 5
  • 46
  • 52
  • 1
    Model binding does not work when using `DisplayFor`, but your answer helped me find this: https://stackoverflow.com/a/11057087/8297552. It seems that hidden field is necessary: "You could accomplish this with a duo of HiddenFor and DisplayFor. Use HiddenFor to have the values ready to be posted, and DisplayFor to show those values" – Łukasz Sypniewski Feb 19 '21 at 12:08
  • @ŁukaszSypniewski Yeah, you will need to add `@Html.HiddenFor(m => m[i].Code)` to pass the value back to the controller since `DisplayFor` doesn't do that automatically. Glad I could help :) – haldo Feb 19 '21 at 12:13
1

The first parameter of LabelFor defines the expression that identifies the property to display and the second parameter displays the texl label.

LabelExtensions.LabelFor Method

@for (var i = 0; i < Model.Count; i++)
{
    <tr>
        <td>@Html.LabelFor(m => m[i].Code, Model[i].Code)</td>
        <td>@Html.TextBoxFor(m => m[i].Price)</td>
    </tr>
}
Meysam Asadi
  • 6,438
  • 3
  • 7
  • 17