Łukasz Sypniewski
Łukasz Sypniewski

Reputation: 715

ASP.NET MVC 5 - LabelFor displays property name instead of value, but TextBoxFor works fine with the same property

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?

Upvotes: 1

Views: 1534

Answers (2)

haldo
haldo

Reputation: 16711

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" />.

Upvotes: 4

persian-theme
persian-theme

Reputation: 6638

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

Upvotes: 1

Related Questions