【问题标题】:formatting amount values in cshtml在cshtml中格式化金额值
【发布时间】:2023-03-21 04:46:01
【问题描述】:

在我看来,如何将AmountFc 属性格式化为#,##0.00

模型中的属性是可以为空的decimal

public decimal? AmountFc { get; set; }

在我使用的视图中

<td height="15" style="text-align:center">@Model.Transcation.AmountFc</td >

使用@Model.Transcation.AmountFc.ToString("#,##0.00") 会出现以下错误。

方法“ToString”没有重载需要 1 个参数

【问题讨论】:

  • 什么是 typeof AmountFc
  • 你在使用ToString()时遇到了什么错误?
  • 它是十进制的?当我尝试使用 ToString("#,##0.00")
  • 编辑您的问题以包含相关详细信息(错误是因为它是一个可为空的属性)
  • 我该如何解决这个问题

标签: asp.net-mvc


【解决方案1】:

使用.ToString("#,##0.###") 时出现的错误是因为该属性是可为空的值类型。您需要将值转换为十进制,例如使用

@Model.Transcation.AmountFc.GetValueOrDefault().ToString("#,##0.00")

但这意味着如果值为null,它将显示0.00,这是一种误导。你可以有条件地检查null,例如

@if(Model.Transcation.AmountFc.HasValue)
{
    <td>@Model.Transcation.AmountFc.Value.ToString("#,##0.00")</td>
}
else
{
    <td></td>
}

但更好的解决方案是将DisplayFormatAttribute 应用于您的属性

[DisplayFormat(DataFormatString = "{0:#,##0.00}")]
public decimal? AmountFc { get; set; }

在视图中,使用

<td>@Html.DisplayFor(m => m.Transcation.AmountFc)</td>

将显示格式化的值(如果值为null,则不显示)

此外,DisplayFormatAttribute 有一个NullDisplayText 属性,用于确定如果值为null(默认为空string)显示什么,例如

[DisplayFormat(DataFormatString = "{0:#,##0.00}", NullDisplayText = "Not applicable")]

会生成

<td>Not applicable</td>

如果值为null

【讨论】:

    猜你喜欢
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    相关资源
    最近更新 更多