ASP.NET Core MVC如何限制input显示double类型小数位数
问题原因
ASP.NET Core MVC的标签辅助程序针对decimal类型做了特殊适配,即使不显式配置编辑模式格式化,也会自动读取[DisplayFormat]特性的规则生成input标签的value属性;但对double、float这类浮点数类型,默认仅在调用DisplayFor等只读显示方法时应用格式化规则,生成编辑控件时会直接输出原始值的默认ToString()结果,因此不会按配置的3位小数显示。
可用解决方案
方案1:开启编辑模式格式化(推荐)
给所有需要格式化的属性的[DisplayFormat]特性添加ApplyFormatInEditMode = true参数,明确告知框架在生成input控件时也应用格式化规则,修改后的模型代码如下:
public class RectangleModel { [DisplayFormat(DataFormatString = "{0:n3}", ApplyFormatInEditMode = true)] public double Length { get; private set; } [DisplayFormat(DataFormatString = "{0:n3}", ApplyFormatInEditMode = true)] public double Width { get; private set; } [DisplayFormat(DataFormatString = "{0:n3}", ApplyFormatInEditMode = true)] public decimal Area { get; private set; } }
该方案在ASP.NET Core 3.0及以上版本均有效,修改后无需调整视图代码,所有引用该模型的视图都会自动按规则格式化显示。
方案2:视图内手动指定格式化值
如果不想修改模型层代码,可以直接在视图的input标签上手动给value属性赋值格式化后的结果,覆盖标签辅助程序的默认输出:
<div class="form-group"> <label asp-for="Width" class="control-label"></label> <input asp-for="Width" value="@string.Format("{0:n3}", Model.Width)" class="form-control" readonly /> <label asp-for="Length" class="control-label"></label> <input asp-for="Length" value="@string.Format("{0:n3}", Model.Length)" class="form-control" readonly /> <label asp-for="Area" class="control-label"></label> <input asp-for="Area" value="@string.Format("{0:n3}", Model.Area)" class="form-control" readonly /> </div>
该方案仅对当前视图生效,适合个别字段需要单独调整格式的场景。
方案3:自定义double类型编辑器模板(全局生效)
如果项目中有大量double类型字段需要统一格式化规则,可以新增全局编辑器模板实现一次配置、全局生效:
- 在
Views/Shared/EditorTemplates路径下新建名为Double.cshtml的视图文件 - 在文件中写入以下模板逻辑:
@model double @{ var format = ViewData.ModelMetadata.DisplayFormatString ?? "{0:G}"; <input asp-for="@Model" value="@string.Format(format, Model)" class="form-control" /> }
配置完成后,所有通过asp-for绑定double类型属性的input控件,都会自动读取属性上[DisplayFormat]配置的格式化规则输出,不需要额外修改单个属性或视图代码。
内容的提问来源于stack exchange,提问作者Francois Louw
相关产品推荐
相关产品推荐

