如何为EntityFramework的DataAnnotations中DisplayName添加CSS样式将Mandatory标红
实现方案
直接在Display特性的Name属性里没法直接嵌入CSS样式,该属性只支持纯文本内容,你可以通过以下两种方式实现需求:
方案1:前端按必填特性判断渲染
- 先调整DataAnnotations代码,去掉DisplayName里的必填标识:
[MaxLength(100)] [Display(Name = "Description")] [Required(ErrorMessage = "Description required")]
- 在前端渲染字段名的位置,判断字段是否标记了
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
相关产品推荐
相关产品推荐

