2017-10-20 36 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