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

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

问题描述

我正在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,但势必会认为它出来作为文本框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 code

.cshtml Code

@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 = "")]

任何想法?

推荐答案

这是如何默认的<一个href=\"http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html\">Decimal编辑模板定义:

<%@ 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} 格式

所以,你有两种可能性:

So you have two possibilities:


  1. 使用双击而不是小数为您的模型类型

  2. 通过创建自定义修改默认编辑器模板〜/查看/共享/ 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小数截断为编辑在小数点后2位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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