如何使用 MVC3 ASP.NET 4.5 和 EF6 基于实体属性注释对 TextBoxFor 进行舍入
Posted
技术标签:
【中文标题】如何使用 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 【发布时间】:2015-05-27 21:55:34 【问题描述】:我正在使用 MVC3、ASP.NET 4.5、EF6、SQL Server 2008、C#、Razor。
我使用 EF6 创建了一个 POCO 实体类作为我的数据的接口。
我希望在从表单保存后将我的小数 (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 一样获取小数的注释舍入指令?
提前谢谢你。
【问题讨论】:
【参考方案1】:没有办法将[DisplayFormat(DataFormatString = "0:F4")]
属性与The Fixed-Point ("F") Format Specifier 一起使用,而您需要与TextBoxFor
助手一起使用。但是您可以使用以下帮助程序重载之一指定格式:
@Html.TextBoxFor(model => model.Decimal1, "0:F4" , new @style = "width:110px" )
【讨论】:
非常感谢,又来救我了!!出于兴趣,与我的另一个问题相关联,是否可以有最多 4 位小数,四舍五入,但如果小于 1.25,那么只保留提供的 2? 刚刚测试了上面的,好像不行。 TextBoxFor 中似乎没有适合“0:F4”的参数。我正在使用 MVC3 中的 Razor1,如果这有影响的话 糟糕,你说得对,这个重载只有 mvc4。我认为唯一的解决方案是明确指定值... 这是我的old answer,但这确实不是一个好习惯 谢谢你.....一个实用的解决方法。继续升级到 MVC4/5 的另一个原因:)以上是关于如何使用 MVC3 ASP.NET 4.5 和 EF6 基于实体属性注释对 TextBoxFor 进行舍入的主要内容,如果未能解决你的问题,请参考以下文章
如何在 asp.net mvc3 中使用 Kendo UI Editor 和剃须刀?
如何在 ASP.NET MVC3 中使用“FormCollection”接收关联数组数据