我试图在 @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 语法有什么问题?
要访问 cost
的 Cost
属性,请使用
@(cost.Cost != 0 ? Html.DisplayFor(m => cost.Cost) + "USD":"-")
旁注:您可能需要考虑使属性 Cost
可以为 null 并在属性上使用 DisplayFormat
属性
[DisplayFormat(DataFormatString = "{0:C}USD", NullDisplayText = "-")]
public decimal? Cost { get; set; }
在这种情况下,您可以将 View 简化为
@Html.DisplayFor(m => cost.Cost)
另请注意,您使用的格式将用于 for
循环,其中 cost
是索引器
for(int i = 0; i < Model.CustomerCost.Count; i++)
{
@Html.DisplayFor(m => m.CustomerCost[i].Cost)
}
我是一名优秀的程序员,十分优秀!