【问题标题】:How to use @Html.DisplayFor in ForEach statement如何在 ForEach 语句中使用 @Html.DisplayFor
【发布时间】:2015-07-11 23:28:34
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    要访问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)
    }
    

    【讨论】:

    • 感谢您的解释。我现在明白了。也感谢您告诉使用数据注释处理可空值。
    • 刚刚添加了另一个解释仅供参考:)
    • 谢谢斯蒂芬·穆克 :)
    • @Stephan,我在我的模型中使用了 [DisplayFormat(DataFormatString = "{0:C0}", NullDisplayText = "-")] 而不是 @Html.DisplayFor(m => cost .Cost) ------ 它显示 0 表示可以为空但不是“-”...任何想法?我认为在我的情况下它不是 null 而是 0.0 所以 NullDisplayText 在这里不起作用。如果我错了,请纠正我?
    • NullDisplayText 的使用仅适用于可为空的类型,因此您的属性需要为public decimal? Cost { get; set; }(或Nullable&lt;decimal&gt;)并且属性的值需要为@987654334 @。我只添加了那个旁注,因为我有点困惑为什么你会将零值显示为 "-" 而不是 "$0.00USD"
    猜你喜欢
    • 2017-01-26
    • 1970-01-01
    • 2016-06-28
    • 2012-01-10
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2012-09-02
    相关资源
    最近更新 更多