2017-10-20 35 views
0

我有一个MVC应用程序,它允许ADM用户动态更改小数位的小数位数。 我需要改变显示格式,所以我写了下面的代码:DecimalDynamicDisplayFormat常量表达式错误

public ForecastProfitView(decimal? literPerUnit = null, int? _decimalPlaces = null) 
    { 
     LiterPerUnit = ((literPerUnit ?? 0) == 0) ? 1 : literPerUnit.Value; 
     decimalPlaces = ((_decimalPlaces ?? 0) == 0) ? 2 : _decimalPlaces.Value; 
    } 

    private decimal LiterPerUnit { get; } 
    private static int decimalPlaces { get; set; } 

    [Display(ResourceType = typeof(Language.App_GlobalResources.AnalysisAndManagement), Name = "BottlingMaterialsCost")] 
    [DecimalDynamicDisplayFormat(decimalPlaces)] 
    public decimal BottlingMaterialsCost { get; set; } 

当我设置[DecimalDynamicDisplayFormat(decimalPlaces)],它给了我一个错误,因为我需要一个常量表达式。有没有办法解决这个问题?

回答

1

不可以。您只能使用编译时常量。基本上所有的东西都可以是const

我会保持格式一个单独的属性,因为它是动态的,这样做:

@Html.TextBoxFor(m => m.BottlingMaterialsCost, bottlingMaterialsCostFormat) 


@Html.TextBoxFor(m => m.BottlingMaterialsCost, "{0:0.00}") 

更新。你可以做这样的事情来计算您的格式:

var bottlingMaterialsCostFormat = ((_decimalPlaces ?? 0) == 0) ? "{0:00}" : "{0:" + new string('0', _decimalPlaces.Value) + "}"; 
+0

无法弄清楚 – Reznor13

+0

我更新了我的答案基于你的'decimalPlaces'财产。主要想法是以某种方式计算该格式。 –

+0

它的工作,非常感谢! – Reznor13