Search code examples
asp.net-mvcwebrazorhtml-helper

Why does Html.DisplayFor show the model property name and not the property value?


I have the following Razor table column:

<td style="width: 300px;">@Html.DisplayFor(m => m.TendersReceived[i].Name)</td>

Yet the client side rendition of the column displays the model property name, i.e. the above displays Name in the Name column, instead of the actual name, the value of the Name property.

More info on the TendersReceived property:

public List<TenSubTenderersQualitySummaryItemViewmodel> TendersReceived { get; set; } = new List<TenSubTenderersQualitySummaryItemViewmodel>();

public class TenSubTenderersQualitySummaryItemViewmodel
{
    public int Number { get; set; }
    public string Name { get; set; }
    public decimal Wq { get; set; }
    public decimal Threshold { get; set; }
    [Display(Name = "Qualify")]
    public bool DoesQualify { get; set; }
    [Display(Name = "Qualify")]
    public string DoesQualifyText => DoesQualify ? "YES" : "NO";
    public string Progress { get; set; }
    [Display(Name = "Staff Acceptability")]
    public string StaffAcceptability { get; set; }
    [Display(Name = "POINTS RANKING")]
    public decimal PointsRanking { get; set; }
    public bool IsNrt { get; set; }
    public decimal PointsTechnical { get; set; }
    public decimal PointsManagement { get; set; }
    public decimal PointsQuality { get; set; }
    public decimal PointsTotal { get; set; }
}

Solution

  • Your use of the

    DisplayFor<TModel,TValue>(HtmlHelper<TModel>, Expression<Func<TModel,TValue>>)

    Returns HTML markup for each property in the object that is represented by the Expression expression.

    is incorrect. It is normally used for templating and one does not normally use DisplayFor for primitive types.

    Using the above would try to render the property name as a label and then its value.

    Name {value here}
    

    if the value is null or empty string, you will only see the label.

    Assuming the collection is a member of the model of the view, simply call the model's member

    <td style="width: 300px;">@Model.TendersReceived[i].Name</td>