c# - 在数据注释的 ErrorMessage 属性中使用 html

标签 c# asp.net-mvc-3 data-annotations

任何人都知道是否可以执行以下操作:

public class User
{
    public Guid UserID { get; set; }

    [Required(ErrorMessage="A school selection is required.")]
    [Range(1, int.MaxValue, ErrorMessage="School not found.  Please contact support at <a href='mailto:support@mysite.com'>support@mysite.com</a>")]
    public int SchoolID { get; set; }

    // ... other properties
}

并且没有 @Html.ValidationMessageFor(model => model.SchoolID) 对 HTML 进行编码?也许我需要为此制作一个自定义帮助程序扩展?有更容易的方法吗?任何指导将不胜感激。如果可以使用辅助扩展,我如何访问辅助扩展方法中的验证规则以确保 html 未被编码?

谢谢。

最佳答案

根据您需要使用它的频率,您可以在验证消息上使用 HttpUtility.HtmlDecode 方法。

@{HttpUtility.HtmlDecode(Html.ValidationMessageFor(x=>x.SchoolId).ToString)}

更可重用但需要更多前期时间的方法是创建您自己的 html 帮助程序(可能称为 HtmlValidationMessageFor()),它返回一个非 html 编码的字符串。

话虽如此,ValidationMessageFor 函数的返回类型是 MvcHtmlString。表示它是

Represents an HTML-encoded string that should not be encoded again.

但是除了它可能是双重编码字符串之外,我找不到关于为什么不应该再次对其进行编码的可靠理由。

关于c# - 在数据注释的 ErrorMessage 属性中使用 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11871495/

相关文章:

asp.net-mvc-2 - ASP.NET MVC 2 显示资源中的名称 DataAnnotation 不起作用

没有等待或返回的 C# 异步任务方法

c# - 在 PRISM 4 中导航到新 View 时如何改进传递对象

c# - ASP.Net C# - 动态删除控件

.net - 由于 .net MVC 中的 HttpContext,测试我的 Controller 引发错误

c# - 如何合并 Html.ActionLink (MVC3) 的 htmlAttributes?

c# - 从 HTML 创建 Word 文档

asp.net-mvc-2 - 如何在 ASP.NET MVC 2 中使用 DataType.Custom?

asp.net-mvc - 将 CSS 类添加到 DataAnnotations MVC 3 中的字段

c# - 松散的 XAML 是根据引用的命名空间加载的 .NET/CLR 版本吗?