When an error occurs on the back-end, the MVC controller returns a message via the
ModelState.AddModelError(\"\", \"message\");
I would like to ha
The ValidationSummary helper HTML encodes error messages and this is by design. It means that you cannot use HTML tags as they will be encoded. So you could write a custom helper which doesn't encode:
public static class ValidationExtensions
{
public static IHtmlString MyValidationSummary(this HtmlHelper htmlHelper)
{
var formContextForClientValidation = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null;
if (htmlHelper.ViewData.ModelState.IsValid)
{
if (formContextForClientValidation == null)
{
return null;
}
if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
{
return null;
}
}
var stringBuilder = new StringBuilder();
var ulBuilder = new TagBuilder("ul");
ModelState modelState;
if (htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out modelState))
{
foreach (ModelError error in modelState.Errors)
{
string userErrorMessageOrDefault = error.ErrorMessage;
if (!string.IsNullOrEmpty(userErrorMessageOrDefault))
{
var liBuilder = new TagBuilder("li");
liBuilder.InnerHtml = userErrorMessageOrDefault;
stringBuilder.AppendLine(liBuilder.ToString(TagRenderMode.Normal));
}
}
}
if (stringBuilder.Length == 0)
{
stringBuilder.AppendLine("");
}
ulBuilder.InnerHtml = stringBuilder.ToString();
TagBuilder divBuilder = new TagBuilder("div");
divBuilder.AddCssClass(htmlHelper.ViewData.ModelState.IsValid ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName);
divBuilder.InnerHtml = ulBuilder.ToString(TagRenderMode.Normal);
if (formContextForClientValidation != null)
{
if (!htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
{
divBuilder.GenerateId("validationSummary");
formContextForClientValidation.ValidationSummaryId = divBuilder.Attributes["id"];
formContextForClientValidation.ReplaceValidationSummary = false;
}
}
return new HtmlString(divBuilder.ToString(TagRenderMode.Normal));
}
}
and then:
@Html.MyValidationSummary()
It is the following line in our custom helper which explicitly doesn't HTML encode:
liBuilder.InnerHtml = userErrorMessageOrDefault;
In the original helper it looks like this:
liBuilder.SetInnerText(userErrorMessageOrDefault);