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

时间:2015-05-02 05:01:33

标签: c# asp.net-mvc razor html-helper

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

以下是我现有的代码:

@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语法有什么问题?

1 个答案:

答案 0 :(得分:2)

要访问Cost使用<{p>的cost属性

@(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)
}
相关问题