如何在 ForEach 语句中使用 @Html.DisplayFor

How to use @Html.DisplayFor in ForEach statement

我正在尝试在 @ForEach 语句中使用 @HTML.DisplayFor 但没有成功。

以下是我现有的代码:

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

但是,我正在尝试替换以下代码行

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

@HTMLDisplayFor

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

@HTML.DisplayFor 语法有什么问题?

要访问 costCost 属性 使用

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

旁注:您可能需要考虑使 属性 Cost 可为空并在 属性

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

在这种情况下,您可以将视图简化为

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

另请注意,您使用的格式将在 for 循环中使用,其中 cost 是索引器

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