MVC3 Decimal 在编辑时被截断为 2 个小数位 [英] MVC3 Decimal truncated to 2 decimal places on edit

查看:16
本文介绍了MVC3 Decimal 在编辑时被截断为 2 个小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Razor 运行 MVC3,并注意到在编辑模式下十进制值被截断为 2 个小数位.我设法通过使用显示格式注释我的属性来绕过它.这似乎不是一个很好的解决方案,因为我必须记住为我生成的每个新视图(或更新我的模板)执行此操作.

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 with a display format. This doesn't seem like a very good solution as I'll have to remember to do this for every new view I generate (or update my templates).

我已经检查了我们的服务返回给控制器的值,它在 1.144 处是正确的,但是当绑定到视图时,它在 TextBox 中显示为 1.14

I have checked the value returned by our service to the controller and it is correct at 1.144, but when bound to the view it comes out as 1.14 in the TextBox

视图模型属性

[Required]
[Display(Name = "Unit Price")]
public decimal UnitPrice { get; set; }

.cshtml 代码

@Html.LabelFor(model => model.UnitPrice) 
@Html.EditorFor(model => model.UnitPrice) 
@Html.ValidationMessageFor(model => model.UnitPrice)

如果我使用以下内容装饰该属性,则它会起作用.

If I decorate the property with the following then it works.

[DisplayFormat(
               ApplyFormatInEditMode = true, 
               DataFormatString = "{0:0.00###########################}", 
               NullDisplayText = "")]

有什么想法吗?

推荐答案

这就是默认的 定义十进制编辑器模板:

<%@ 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" }) %>

注意 {0:0.00} 格式.

所以你有两种可能:

  1. 在模型中使用 double 而不是 decimal 作为类型
  2. 通过创建自定义 ~/Views/Shared/EditorTemplates/Decimal.cshtml 来修改默认编辑器模板,它可能看起来像这样:

  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.

这篇关于MVC3 Decimal 在编辑时被截断为 2 个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆