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. <a href="%url_token%">Click here to reset.</a></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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With