Search code examples
c#asp.net-mvcrazorhtml-helper

How to use @Html.DisplayFor in ForEach statement


I am trying to use @HTML.DisplayFor in @ForEach statement but not successful.

The following is my existing code:

@foreach (var cost in Model.CustomerCost)
{
    <tr>
        <td>@cost .CustomerName</td>
        <td>@(cost.Cost!= 0 ? string.Format("{0:C}", cost.Cost) + " USD" : "-")</td>
    </tr>
}

However, i am trying to replace the following line of code

<td>@(cost.Cost!= 0 ? string.Format("{0:C}", cost.Cost) + " USD" : "-")</td>

with

@HTMLDisplayFor

<td>@(cost.Cost!= 0 ? Html.DisplayFor(model => model.CustomerCost[cost].Cost + "USD":"-")</td>

What is wrong in @HTML.DisplayFor syntax?


Solution

  • To access the Cost property of cost use

    @(cost.Cost != 0 ? Html.DisplayFor(m => cost.Cost) + "USD":"-")
    

    Side note: You may want to consider making property Cost nullable and using the DisplayFormat attribute on the property

    [DisplayFormat(DataFormatString = "{0:C}USD", NullDisplayText = "-")]
    public decimal? Cost { get; set; }
    

    in which case you can simplify the view to just

    @Html.DisplayFor(m => cost.Cost)
    

    Note also the format you were using would be used in a for loop where cost is the indexer

    for(int i = 0; i < Model.CustomerCost.Count; i++)
    {
      @Html.DisplayFor(m => m.CustomerCost[i].Cost)
    }