Formatting currency using display template in MVC

为君一笑 提交于 2019-12-04 03:30:38

How about HtmlHelper that checks the ViewData["woCurrency"] automatically and outputs the correct result?

    public static string Currency(this HtmlHelper helper, decimal data, string locale = "en-US", bool woCurrency = false)
    {
        var culture = new System.Globalization.CultureInfo(locale);

        if (woCurrency || (helper.ViewData["woCurrency"] != null && (bool)helper.ViewData["woCurrency"]))
            return data.ToString(culture);

        return data.ToString("C", culture);
    }

Then:

@Html.Currency(Model.Money);
Husein Roncevic

You need to apply DisplayFormat attribute to your Money property. For example:

[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Money { get; set; }

For more information have a look at these two links:

  1. DisplayFormatAttribute.DataFormatString (The example at the bottom of the page uses currency formatting as an example)
  2. ASP.NET MVC - DisplayFormat attribute
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!