如何基于实体 属性 注释,使用 MVC3 ASP.NET 4.5 和 EF6 让 TextBoxFor 进行舍入

How to get TextBoxFor to round, based on Entity Property Annotations, using MVC3 ASP.NET 4.5 and EF6

我正在使用 MVC3、ASP.NET 4.5、EF6、SQL Server 2008、C#、Razor。

我使用 EF6 创建了一个 POCO 实体 class 作为我的数据的接口。

我希望在从表单保存后将我的小数 (20,4) 属性四舍五入。目前前 4 位小数与第 5 位小数无关,即没有舍入

我得到:

1.234567 -> 1.2345

我要:

1.234567 -> 1.2346

最好使用注释在实体 属性 级别具体说明。我玩过 DataFormatString,它适用于 "DisplayFor",但不适用于 "TextBoxFor"。

@Html.TextBoxFor(model => model.Decimal1, new { style = "width:110px" })

我的实体 属性 代码是:

    [System.ComponentModel.DataAnnotations.DisplayFormat(DataFormatString = @"{0:G29}")]
    [System.ComponentModel.DataAnnotations.RegularExpression(@"^[0-9]\d*(.\d+)?$", ErrorMessage = @"* Must be a number")]
    [System.ComponentModel.DisplayName("Decimal1 Value")]
    public virtual global::System.Nullable<decimal> Decimal1
    {
        get
        {
            return _Decimal1;
        }
        set
        {
            _Decimal1 = value;
        }
    }

如何让 @Html.TextBoxFor 像 DisplayFor 一样获取小数的注释舍入指令?

提前致谢。

无法将 [DisplayFormat(DataFormatString = "{0:F4}")] 属性与 The Fixed-Point ("F") Format Specifier 一起使用,您需要 TextBoxFor 助手。但是您可以使用这样的辅助重载之一指定格式:

@Html.TextBoxFor(model => model.Decimal1, "{0:F4}" , new { @style = "width:110px" })