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

如何为EntityFramework的DataAnnotations中DisplayName添加CSS样式将Mandatory标红

实现方案

直接在Display特性的Name属性里没法直接嵌入CSS样式,该属性只支持纯文本内容,你可以通过以下两种方式实现需求:

方案1:前端按必填特性判断渲染

  1. 先调整DataAnnotations代码,去掉DisplayName里的必填标识:
[MaxLength(100)]
[Display(Name = "Description")]
[Required(ErrorMessage = "Description required")]
  1. 在前端渲染字段名的位置,判断字段是否标记了Required特性,动态追加带红色样式的必填提示,以ASP.NET MVC/Razor Pages为例:
<label>
    @Html.DisplayNameFor(m => m.Description)
    @if (ViewData.ModelMetadata.IsRequired)
    {
        <span style="color: red"> (*Mandatory)</span>
    }
</label>

方案2:自定义Display特性内嵌HTML

如果需要在后台统一控制显示逻辑,可以自定义继承自DisplayAttribute的子类,允许返回带HTML标签的内容:

public class DisplayWithMandatoryAttribute : DisplayAttribute
{
    public new string Name => $"{base.Name} <span style=\"color:red\">(*Mandatory)</span>";
}

// 业务代码调用
[MaxLength(100)]
[DisplayWithMandatory(Name = "Description")]
[Required(ErrorMessage = "Description required")]

前端渲染时使用@Html.Raw(Html.DisplayNameFor(m => m.Description))输出非转义的HTML内容即可正常显示红色的Mandatory文本。

内容的提问来源于stack exchange,提问作者ZooHit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 05:21:03