为Model属性设置DisplayFormat后未生效,请求技术帮助
问题解决:DisplayFormat特性未生效的原因及修复方案
问题根源分析
你的代码存在三个关键问题导致格式化失效:
- Razor标签语法错误:input标签的
asp-for属性引号未闭合,class属性写法也有语法错误,导致ASP.NET Core无法正确解析数据注解特性。 - DisplayFormat特性未开启编辑模式支持:默认情况下
DisplayFormat仅在显示场景(如DisplayFor)生效,编辑模式下需要显式设置ApplyFormatInEditMode = true。 - 手动覆盖value值:你手动设置了
value="@Model.Contacts[i].Deductible",这会覆盖asp-for根据特性自动生成的格式化值。
修复步骤
1. 修正模型的DisplayFormat特性
更新Contact类的Deductible字段,添加ApplyFormatInEditMode = true:
public class Contact { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public DateTime HireDate { get; set; } [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = true)] public decimal Deductible { get; set; } }
2. 修正CSHTML中的Razor标签
修复input标签的语法错误,移除手动设置的value属性,让asp-for自动处理格式化:
@for (var i = 0; i < Model.Contacts.Count; i++) { <div class="col-sm"> <label asp-for="@Model.Contacts[i].Deductible" class="control-label"></label> <input asp-for="@Model.Contacts[i].Deductible" class="form-control" /> </div> }
说明
asp-for标签助手会自动读取模型上的DisplayFormat特性,开启ApplyFormatInEditMode后,输入框会显示格式化后的货币值。- 必须移除手动的
value赋值,否则会覆盖标签助手生成的格式化内容。
内容的提问来源于stack exchange,提问作者Mark C
相关产品推荐
相关产品推荐

