货币格式的ASP.NET MVC数据注释 [英] ASP.NET MVC data annotation for currency format

查看:106
本文介绍了货币格式的ASP.NET MVC数据注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我关注POCO,其中费用"为浮动金额.

I have following POCO with Cost as float.

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.

$U 4.882,50.

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

What data annotation should I use?

这就是我在视图中显示的方式.

This is how I am displaying in my view.

<td>@Model.Cost</td>

推荐答案

您是否尝试过使用DataType.Currency:

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

}

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

Alternatively, you could use DataFormatString like this:

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

但是我更喜欢使用EditorFor设置显示格式.这是有关扩展的很棒的教程ASP.NET MVC编辑器模板教程.

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

这样,您只需在一个地方编写货币的显示逻辑,就不需要每次想显示货币金额时都添加提取注释.

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.

-编辑

要使其在EditorFor中工作,您还可以在DataFormatString的末尾添加ApplyFormatInEditMode = true,使该行为:

To make it work in EditorFor, you can also add ApplyFormatInEditMode = true to the end of the DataFormatString making the line as:

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

这篇关于货币格式的ASP.NET MVC数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆