2017-04-17 74 views
1

這是場我在我的視圖模型:爲什麼剃鬚刀會自動舍入到小數點後兩位小數位?

public decimal MyValue { get; set; } 

這是我如何顯示在視圖中值:

@Html.EditorFor(model => model.MyValue) 

我調試從DB一路關閉所有的JS 。我仍然在View中獲得該模型的值爲12.34345,但呈現給用戶的最終值是12.34。

This問題是問如何解決這個問題,但爲什麼不清楚。

有趣的是,當我使用:

@Html.HiddenFor(model => model.MyValue) 

四捨五入沒有發生。

回答

0

它是decimal的默認EditorTemplate的函數。形成source code(注意格式"{0:0.00}"

internal static string DecimalTemplate(HtmlHelper html) 
{ 
    if (html.ViewContext.ViewData.TemplateInfo.FormattedModelValue == html.ViewContext.ViewData.ModelMetadata.Model) 
    { 
     html.ViewContext.ViewData.TemplateInfo.FormattedModelValue = String.Format(CultureInfo.CurrentCulture, "{0:0.00}", html.ViewContext.ViewData.ModelMetadata.Model); 
    } 
    return StringTemplate(html); 
} 

如果你想要顯示的小數位保存,使用@Html.TextBoxFor(m => m.MyValue),或者您可以使用DisplayFormatAttribute,將由EditorFor()方法得到尊重應用自己的格式,例如

[DisplayFormat(DataFormatString = "{0:0.00000}", ApplyFormatInEditMode = true)]` 
public decimal MyValue { get; set; } 
+2

'[DisplayFormat(DataFormatString =「{0:F5}」,ApplyFormatInEditMode = true)]'也適用。 –

0

請看看在低於源代碼 https://github.com/aspnet/Mvc/blob/6436538068d19c475d5f7c9ce3d0080d2314f69d/src/Microsoft.AspNetCore.Mvc.ViewFeatures/Internal/DefaultEditorTemplates.cs

參見下文方法

public static IHtmlContent DecimalTemplate(IHtmlHelper htmlHelper) 
{ 
     if (htmlHelper.ViewData.TemplateInfo.FormattedModelValue == htmlHelper.ViewData.Model) 
     { 
      htmlHelper.ViewData.TemplateInfo.FormattedModelValue = 
       string.Format(CultureInfo.CurrentCulture, "{0:0.00}", htmlHelper.ViewData.Model); 
     } 

     return StringTemplate(htmlHelper); 
} 
+1

這個問題被標記爲['asp.net-mvc'](http://stackoverflow.com/questions/tagged/asp.net-mvc)而不是['asp.net-core'](http:// stackoverflow.com/questions/tagged/asp.net-core) – mmushtaq

+0

感謝您的評論,但我真的沒有看到有任何差異在這兩個。 –

相關問題