Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent MVC3 html escaping my validation messages?

Tags:

asp.net-mvc

I'm trying to output a validation message in MVC3 which contains a link.

I'm outputting the error message place holder like this

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

The problem is, the error message is html escaped which is fine most times, but I'd like a link to be in the middle.

<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>

How do I prevent this from happening?

This works but is not a solution, rather, a temporary work around.

@{
  string s = Html.ValidationMessageFor(model => model.Email).ToString();
}
@Html.Raw(HttpUtility.HtmlDecode(s))
like image 650
Razor Avatar asked Nov 14 '22 21:11

Razor


1 Answers

Looking at the code with reflector it doesn't seem to have a method for that, the more complete overload is:

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)));
}

What you can do however is to create an extension method that returns the string as you want, like this:

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());
    }
}

You can use a MvcHtmlString. See MvcHtmlString.Create(). It will output the html without escaping.

like image 164
BrunoLM Avatar answered Dec 18 '22 10:12

BrunoLM