如何防止MVC3 html转义我的验证消息?

时间:2011-06-17 11:57:31

标签: asp.net-mvc

我正在尝试在MVC3中输出包含链接的验证消息。

我正在输出错误信息占位符,如此

@Html.ValidationMessageFor(model => model.Email)

问题是,错误消息是html转义,这很好,但我想要一个链接在中间。

<span class="field-validation-error" data-valmsg-for="Email" data-valmsg-replace="true">This e-mail address is already registed. &lt;a href=&quot;%url_token%&quot;&gt;Click here to reset.&lt;/a&gt;</span>

如何防止这种情况发生?

这有效,但不是解决方案,而是临时工作。

@{
  string s = Html.ValidationMessageFor(model => model.Email).ToString();
}
@Html.Raw(HttpUtility.HtmlDecode(s))

2 个答案:

答案 0 :(得分:1)

使用反射器查看代码似乎没有方法,更完整的重载是:

public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
    string validationMessage,
    object htmlAttributes)
{
    return htmlHelper.ValidationMessageFor<TModel, TProperty>(expression, validationMessage, ((IDictionary<string, object>) HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)));
}

然而,您可以创建一个扩展方法,根据需要返回字符串,如下所示:

public static class ValidationExtender
{
    public static IHtmlString HtmlValidationMessageFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression)
    {
        return MvcHtmlString.Create(htmlHelper.ValidationMessageFor(expression).ToHtmlString());
    }
}

您可以使用MvcHtmlString。见MvcHtmlString.Create()。它将输出html而不转义。

答案 1 :(得分:0)

以@ BrunoLM为首,以下扩展方法应该能满足您的需求。我只对此进行了基本测试,但确实有效。

public static class HtmlHelperExtensions
{
    private static readonly string htmlErrorPlaceholder = "##__html#Error#Placeholder__##";

    public static IHtmlString HtmlValidationMessageFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        object htmlAttributes)
        {
            var name      = expression.GetMemberName();
            var isInError = htmlHelper.ViewContext.ViewData.ModelState.ContainsKey(name);
            var message   = htmlHelper.ValidationMessageFor(expression, htmlErrorPlaceholder, htmlAttributes);
            if (isInError && !MvcHtmlString.IsNullOrEmpty(message))
            {
                var realError = htmlHelper.ViewContext.ViewData.ModelState[name].Errors.First().ErrorMessage;
                return htmlHelper.Raw(message.ToString().Replace(htmlErrorPlaceholder, realError));
            }

            return MvcHtmlString.Empty;
        }
}

public static class Expression_1Extensions
{
    public static string GetMemberName<TModel, TProperty>(this Expression<Func<TModel, TProperty>> expression)
    {
        switch (expression.Body.NodeType)
        {
            case ExpressionType.MemberAccess:
                MemberExpression memberExpression = (MemberExpression)expression.Body;
                return memberExpression.Member is PropertyInfo ? memberExpression.Member.Name : null;
        }

        throw new NotSupportedException();
    }
}