gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:31:34 24 4
gpt4 key购买 nike

我试图在 @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 可以为 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)
}

关于c# - 如何在 ForEach 语句中使用 @Html.DisplayFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29998609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com