【问题标题】:How should I use EditorFor() in MVC for a currency/money type?我应该如何在 MVC 中将 EditorFor() 用于货币/货币类型?
【发布时间】:2011-07-02 02:45:08
【问题描述】:

在我看来,我有以下电话。

<%= Html.EditorFor(x => x.Cost) %>

我有一个带有以下代码的 ViewModel 来定义成本。

public decimal Cost { get; set; }

但是,这会显示小数点后四位数的十进制值(例如 0.0000)。我知道Decimal.toString("G") (MSDN) 似乎可以解决这个问题,但我不确定在哪里应用它。

一种解决方案似乎是创建一个局部视图“Currency.aspx”。

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Decimal>" %>
<%= Html.TextBox(Model.ToString("g"), new { @class = "currency" }) %>

在我的 ViewModel 中还有一个 [UIHint("Currency")]

这似乎不优雅。我认为这个问题已经在 MVC 框架或 C# 的某个地方得到了很好的解决,但我不知道更干净的解决方案。

在 MVC 中处理编辑货币值的适当方法是什么?

【问题讨论】:

    标签: c# asp.net-mvc currency


    【解决方案1】:
    [DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
    public decimal Cost { get; set; }
    

    在你看来:

    <%= Html.EditorFor(x => x.Cost) %>
    

    仅此而已。

    您可能想要应用自定义 CSS 类。你可以这样做:

    <div class="currency">
        <%= Html.EditorFor(x => x.Cost) %>
    </div>
    

    然后在你的css中:

    .currency input {
        /** some CSS rules **/
    }
    

    write a custom DataAnnotationsModelMetadataProvider,您可以:

    [DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
    [HtmlProperties(CssClass = "currency")]
    public decimal Cost { get; set; }
    

    然后在你看来:

    <%= Html.EditorFor(x => x.Cost) %>
    

    【讨论】:

    • 此版本中没有@class= "currency"。
    • 如果您只有几个货币字段要显示编辑器,那就太好了。如果您将在整个应用程序中重复,Currency.aspx 方法是合适的。
    • @DarinDimitrov,我尝试对 TextBoxFor 进行相同的尝试,但失败了。我已经在这里解释了stackoverflow.com/questions/14700873/…。似乎 InputHelper 类没有考虑 FormatStrings :(
    • @Murali,你失败很正常。 DisplayFormat 属性旨在与模板化助手一起使用,例如 EditorForDisplayFor。您不能将它与TextBoxFor 一起使用。我已经发布了您的问题的答案。
    • @DarinDimitrov,您链接到“自定义 DataAnnotationsModelMetadataProvider”的文章正在使用 MVC 2 和 Ascx 文件。您是否知道另一个涵盖 MVC 4 或 5 尤其是 Razor 的教程?
    【解决方案2】:

    如果您使用的是 EditorFor 模板,这是合适的方式。

    “非常不优雅”是什么意思?

    【讨论】:

    • 这意味着解决方案中有很多丑陋的代码。解决格式错误,应该由语言或框架直接解决(我们谈论的是货币类型,而不是一些晦涩的想法),不应该需要跨两个文件的 3 行代码,这两个文件实际上都不包含对 EditorFor( )。
    • @Thomas Langston ROFL!您正在使用基于元数据的模板引擎,它删除了数百行样板 html + c# 代码,并且不知何故,两个文件中的 3 行太多了?
    猜你喜欢
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多