【问题标题】:How to create custom DisplayFormat for Decimal property in mvc?如何在 mvc 中为 Decimal 属性创建自定义 DisplayFormat?
【发布时间】:2018-04-04 15:06:07
【问题描述】:

我有一个十进制类型的网格属性 -

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

我希望 [DisplayFormat 自定义以接受不同行的不同值,例如 -

第 1 行的单价 ~ 仅显示 2 位小数 {0:0.00}

第 2 行的单价 ~ 显示 4 位小数 - {0:0.0000}

小数点后的值来自数据库,我将它们作为另一个属性存储在模型中 -

public int UnitsDecimals { get; set; }

我已经在使用编辑器和显示模板了。我应该创建自定义 htmlhelper 吗?如果是,如何将 UnitsDecimal 的值传递给自定义助手?

【问题讨论】:

  • 你在哪里编写代码以获得正确的行格式。
  • 自定义需求

标签: asp.net-mvc customization html-helper


【解决方案1】:

您可以在视图模型中添加其他属性来指示数据的来源。

      public class ViewModel {
        public decimal? UnitPrice { get; set; }  
        //This Changes as per source 
        public string  PriceNumberFormatString{get;set;}
       }

对于来自数据源的不同十进制输入值,您可以使用详细的 PriceNumberFormatString getter setter..

然后在 View 中,您可以使用 PriceNumberFormatString 的值来操作 UnitPrice 的视图。操作取决于您的 UI 库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2011-10-23
    • 1970-01-01
    • 2013-08-29
    • 2016-01-20
    相关资源
    最近更新 更多