You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为Model属性设置DisplayFormat后未生效,请求技术帮助

问题解决:DisplayFormat特性未生效的原因及修复方案

问题根源分析

你的代码存在三个关键问题导致格式化失效:

  1. Razor标签语法错误:input标签的asp-for属性引号未闭合,class属性写法也有语法错误,导致ASP.NET Core无法正确解析数据注解特性。
  2. DisplayFormat特性未开启编辑模式支持:默认情况下DisplayFormat仅在显示场景(如DisplayFor)生效,编辑模式下需要显式设置ApplyFormatInEditMode = true。
  3. 手动覆盖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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:22:31