Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Add XHTML into validation error messages

Just starting with ASP.Net MVC and have hit a bit of a snag regarding validation messages. I've a custom validation attribute assigned to my class validate several properties on my model.

When this validation fails, we'd like the error message to contain XHTML mark-up, including a link to help page, (this was done in the original WebForms project as a ASP:Panel).

At the moment the XHTML tags such as "< a >", in the ErrorMessage are being rendered to the screen. Is there any way to get the ValidationSummary to render the XHTML markup correctly? Or is there a better way to handle this kind of validation?

Thanks

like image 990
Neil Avatar asked Dec 29 '22 22:12

Neil


2 Answers

Here's a short-term fix that uses HtmlDecode() to reverse the encoding. Works for me.

(Couldn't be bothered rebuilding the whole Validation object model.)

public static class ValidationExtensions
{
  public static MvcHtmlString ValidationMessageHtmlFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression)
  {
    return new MvcHtmlString(
      HttpUtility.HtmlDecode(
        htmlHelper.ValidationMessageFor<TModel, TProperty>(
        expression, 
        null, 
      ((IDictionary<string, object>)new RouteValueDictionary()))
        .ToHtmlString()));
  }
}
like image 128
Jonathan Avatar answered Jan 11 '23 21:01

Jonathan


I'm pretty sure that the default validation message helpers HTML encode any message that you might have in your attribute. My suggestion would be to use the source code available on CodePlex as a starting point to write your own HtmlHelper extension that doesn't do HTML encoding on the error string. You want to look in the System.Web.Mvc.Html namespace for the ValidationExtensions.cs file.

like image 23
tvanfosson Avatar answered Jan 11 '23 23:01

tvanfosson