我尝试在@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语法有什么问题?
答案 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)
}