对于货币格式ASP.NET MVC数据注解

问题描述 投票:19回答:5

我曾与成本浮法以下POCO。

public class CostChart
{
    public string itemType { get; set; }
    public float? Cost{ get; set; }

}

我需要在货币格式返回例如成本

在$ 4,882.50。

我应该使用什么数据注解?

这是我如何在我的视图中显示。

<td>@Model.Cost</td>
asp.net-mvc
5个回答
44
投票

您是否尝试过使用DataType.Currency

public class CostChart
{
    public string itemType { get; set; }
    [DataType(DataType.Currency)]
    public float? Cost{ get; set; }

}

另外,您也可以使用DataFormatString这样的:

[DisplayFormat(DataFormatString = "{0:C0}")]`
public float? Cost{ get; set; }

但我更喜欢用设置在EditorFor显示格式。这里有Extending Editor Templates for ASP.NET MVC教程伟大的教程。

这样一来,你写你的货币的显示逻辑只在一个地方,你不需要添加注释提取要显示的货币金额每一次。

- 编辑

为了使其在EditorFor工作,你也可以ApplyFormatInEditMode = true添加到拍行作为DataFormatString的结尾:

[DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]

10
投票

尝试使用:

 [DisplayFormat(DataFormatString = "{0:C0}")]

访问这个帖子https://stackoverflow.com/a/19800496/3642086


4
投票

尝试这个 :

public class CostChart
  {
    public string itemType { get; set; }

    [DataType(DataType.Currency)]
    public float? Cost{ get; set; }
  }

如果你还没有看到$符号,在web.config中正在写入这行代码

<globalization culture ="en-us"/>

0
投票

请参阅这篇文章(Codeculous.)的另一种方法来验证和不设定全球化与只是通过将数据注释DataType(DataType.Currency)显示各自的货币符号。


0
投票

您可以在Razor视图做

@string.Format("{0:0,0.00,00}", Model.Cost)
© www.soinside.com 2019 - 2024. All rights reserved.