asp.net-mvc 货币格式的 ASP.NET MVC 数据注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29975128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:26:34  来源:igfitidea点击:

ASP.NET MVC data annotation for currency format

asp.net-mvc

提问by immirza

I have following POCO with Cost as float.

我关注 POCO,成本为浮动。

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

}

I need to return Cost in currency format e.g.

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

$U 4.882,50.

4.882,50 美元。

What data annotation should I use?

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

This is how I am displaying in my view.

这就是我在我看来的显示方式。

<td>@Model.Cost</td>

回答by Cacho Santa

Have you tried using DataType.Currency:

您是否尝试过使用DataType.Currency

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

}

Alternatively, you could use DataFormatStringlike this:

或者,您可以DataFormatString像这样使用:

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

But I prefer to set the display format with EditorFor. Here's a great tutorial on Extending Editor Templates for ASP.NET MVCtutorial.

但我更喜欢用EditorFor. 这是一个关于为 ASP.NET MVC教程扩展编辑器模板的很棒的教程。

That way, you write the display logic of your currencies in just ONE place, and you don't need to add that extract annotation every single time you want to display a currency amount.

这样,您只需在一处编写货币的显示逻辑,而无需在每次要显示货币金额时都添加提取注释。

--Edit

- 编辑

To make it work in EditorFor, you can also add ApplyFormatInEditMode = trueto the end of the DataFormatStringmaking the line as:

要使其在 EditorFor 中工作,您还可以添加ApplyFormatInEditMode = trueDataFormatString制作行的末尾:

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

回答by Márcio Gonzalez

Try using:

尝试使用:

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

Visit this post https://stackoverflow.com/a/19800496/3642086

访问这篇文章 https://stackoverflow.com/a/19800496/3642086

回答by Rachit Thakur

try this :

尝试这个 :

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

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

if you still do not see $ symbol, in web.config under write this line of code

如果还是没有看到$符号,在web.config下写这行代码

<globalization culture ="en-us"/>

回答by Guruprakash

Check out this article(Codeculous.) an alternate way to validate and display the respective currency symbols without setting Globalization and just by adding the data annotations DataType(DataType.Currency).

查看这篇文章 ( Codeculous.) 验证和显示相应货币符号的另一种方法,无需设置全球化,只需添加数据注释DataType(DataType.Currency)

回答by venogn

You can do in RazorView

你可以在 RazorView 中做

@string.Format("{0:0,0.00,00}", Model.Cost)