MVC3 Decimal truncated to 2 decimal places on edit

前端 未结 3 1459
一向
一向 2020-12-05 02:48

I\'m running MVC3 with Razor and noticed that decimal values are truncated to 2 decimal places when in edit mode. I\'ve managed to get round it by annotating my property wit

相关标签:
3条回答
  • 2020-12-05 03:13

    If you don't need the functionality of the 'EditorFor' HtmlHelper, you can simply swap it out for the 'TextBoxFor' and it shouldn't truncate your decimal value...

    0 讨论(0)
  • 2020-12-05 03:17

    IMO, this article has a better option:

    html-editorfor-with-3-decimal-places

    I used this code to display up to 4 decimal digits in my EditFor:

        [Display(Name = "Discount Percentage")]
        [Range(0, 100.0)]
        [DisplayFormat(DataFormatString="{0:0.0000}", ApplyFormatInEditMode=true)]
        public Decimal? DiscountPercent { get; set; }
    
    0 讨论(0)
  • 2020-12-05 03:32

    That's how the default Decimal editor template is defined:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    <script runat="server">
        private object ModelValue {
            get {
                if (ViewData.TemplateInfo.FormattedModelValue == ViewData.ModelMetadata.Model) {
                    return String.Format(
                        System.Globalization.CultureInfo.CurrentCulture,
                        "{0:0.00}", ViewData.ModelMetadata.Model
                    );
                }
                return ViewData.TemplateInfo.FormattedModelValue;
            }
        }
    </script>
    <%= Html.TextBox("", ModelValue, new { @class = "text-box single-line" }) %>
    

    Notice the {0:0.00} format.

    So you have two possibilities:

    1. Use double instead of decimal as type in your model
    2. Modify the default editor template by creating a custom ~/Views/Shared/EditorTemplates/Decimal.cshtml which might simply look like this:

      @Html.TextBox(
          "", 
          ViewData.TemplateInfo.FormattedModelValue, 
          new { @class = "text-box single-line" }
      )
      

    You probably might want to modify the display template as well.

    0 讨论(0)
提交回复
热议问题