【问题标题】:String.Format for currency on a TextBoxForTextBoxFor 上货币的 String.Format
【发布时间】:2011-08-05 23:04:52
【问题描述】:

我正在尝试让@String.Format("{0:0.00}",Model.CurrentBalance) 进入这个@Html.TextBoxFor(model => model.CurrentBalance, new { @class = "required numeric", id = "CurrentBalance" })

我只是希望货币在我的文本框中显示为 .00,但我没有运气。关于我如何做到这一点的任何想法?

【问题讨论】:

    标签: c# asp.net-mvc-3 string.format


    【解决方案1】:

    string.format("{0:c}", Model.CurrentBalance) 应该为您提供货币格式。

    @Html.TextBoxFor(model => model.CurrentBalance, new { @class = "required numeric", id = "CurrentBalance", Value=String.Format("{0:C}",Model.CurrentBalance) })

    【讨论】:

    • @Html.TextBoxFor(String.Format("{0:C}",model => model.CurrentBalance), new { @class= "required numeric", id = "CurrentBalance" }) ....这是我要找的风格吗?
    • @Html.TextBoxFor(model => model.CurrentBalance, new { @class= "必需的数字", id = "CurrentBalance", Value=String.Format("{0:C}", Model.CurrentBalance) })...这就是我要找的。谢谢你的帮助:)
    • 值得注意的是,货币符号取决于您的区域设置。在欧洲部分地区,您将获得一百万美元的$1.000.000,00,根据设置,您可能会获得($20.00)-$20.00 的底片。
    • 为什么Value 中的“v”必须是大写字母?
    • 这是一个黑客。它之所以有效,只是因为“价值”优先于“价值”。这不应该是公认的答案。
    【解决方案2】:
    @Html.TextBoxFor(model => model.CurrentBalance, "{0:c}", new { @class = "required numeric", id = "CurrentBalance" })
    

    这让您可以设置格式并添加任何额外的 HTML 属性。

    【讨论】:

    • 考虑为您的答案添加解释。
    • 这是正确答案。当前接受的答案是hack。它产生 2 个值属性,“值”和“值”。
    【解决方案3】:

    虽然Dan-o's 解决方案有效,但我发现它在使用基于表单的 TempData 时存在问题(请参阅ImportModelStateFromTempData and ExportModelStateToTempData)。对我有用的解决方案是 David Spence's 在相关线程上。

    具体来说:

    [DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]
    public decimal? Price { get; set; }
    

    现在,如果您在视图中使用 EditorFor,则应应用注释中指定的格式,并且您的值应以逗号分隔:

    <%= Html.EditorFor(model => model.Price) %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多