【问题标题】:Format to Currency using DisplayFor Html Helper使用 DisplayFor Html Helper 格式化为货币
【发布时间】:2017-03-13 20:57:21
【问题描述】:

我的页面会显示一些货币数据。 我想用货币格式格式化数据,但只使用显示模板。

我有以下代码:

 @foreach (var item in Model.Data)
{
    <tr class="@(item.Group%2==0? "odd-colore": "even-colore")">
    <td>@Html.DisplayFor(modelItem => item.Name)</td>
    <td>@Html.DisplayFor(modelItem => item.Amount1)</td>      
    <td>@Html.DisplayFor(modelItem => item.LName)</td>
    <td>@Html.DisplayFor(modelItem => item.Amount2)</td>
    <td>@Html.DisplayFor(modelItem => item.Amount3)</td>

    </tr>
}   

我创建了一个DisplayTemplateString.cshtml,因为我的数据类型是字符串:

@model string

@{ 
    IFormatProvider formatProvider = new System.Globalization.CultureInfo("en-US");
    <span class="currency">@Model.ToString("C",formatProvider)</span>
}

但是当我运行它时,我得到了错误:

方法 'ToString' 没有重载需要 2 个参数

如何使用 DisplayTemplatestring.Format("{0:C}") 将正数显示为 $1000.00,将负数显示为 ($1000.00)

【问题讨论】:

    标签: asp.net-mvc display-templates


    【解决方案1】:

    您遇到的问题是因为您试图将 string 转换为货币。来自MSDN

    货币(“C”)格式说明符

    “C”(或货币)格式说明符将数字转换为表示货币金额的字符串

    您尝试使用的 .ToString(string format, IFormatProvider formatProvider) 重载仅存在于数字类型,这就是它无法编译的原因。

    作为一个例子来证明这一点:

    public class TestModel
    {
        public decimal Amount { get; set; }
        public string StringAmount { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var model = new TestModel
            {
                Amount = 1.99M,
                StringAmount = "1.99"
            };
    
            IFormatProvider formatProvider = new CultureInfo("en-US");
    
            // Prints $1.99
            Console.WriteLine(model.Amount.ToString("C", formatProvider));
    
            // Prints 1.99
            Console.WriteLine(string.Format(formatProvider, "{0:C}", model.StringAmount));
        }
    }
    

    所以你有几个选择:

    1. 将您的数据转换为模板中的数字类型,然后对其进行格式化。
    2. 首先将您的数据存储为数字类型。

    我相信 2 是更好的选择,因为您希望使用数字数据,因此将其存储为字符串只会增加计算和格式化时的复杂性(如您在此处看到的),因为您是总是必须先执行转换。

    【讨论】:

    • 很遗憾,我无法将数据存储为数字,因为有时我可能会得到一个空字符串作为金额。我的属性是一个字符串类型,用于映射到从数据库返回的 xml 属性,该属性可以包含一个空字符串
    • 很遗憾,我无法将数据存储为数字,因为有时我可能会得到一个空字符串作为金额。我的属性是一个字符串类型,用于映射到从数据库返回的 xml 属性,该属性可以包含一个空字符串。所以,基本上,我需要使用@model string。但是,由于它在DIsplayTemplate 内部,我不确定如何将它用于@Html.DisplayFor(modelItem =&gt; item.Data.ProductCost, "Currency" 格式的特定列。我的显示模板名为“货币”
    • @gene 很抱歉没有尽快回复。 Html.DisplayFor 的重载确实将模板名称作为第二个参数,因此您的 @Html.DisplayFor(modelItem =&gt; item.Data.ProductCost, "Currency") 示例实际上应该可以工作。如果不是,那将是因为它无法找到模板。您还可以在模型的属性上使用UIHint attribute
    猜你喜欢
    • 2020-03-05
    • 2013-10-18
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    相关资源
    最近更新 更多