How to include a link in AddModelError message?

Viewed 8818

I want to add a ModelState error, like so:

ModelState.AddModelError("", "Some message, <a href="/controller/action">click here</a>)

However, the link doesn't get encoded, and so is displayed like text. I tried using

<%= Html.ValidationSummary(true, "Some message")

instead of

<%: Html.ValidationSummary(true, "Some message")

But no luck.

Anyone have any idea how to get this working?

Cheers

4 Answers

Using HttpUtility.HtmlDecode or @Html.Raw as suggested in other answers introduces a reflected XSS issue because user input is reflected as part of the error message.

The ASP.NET Framework by default will block HTML and return a validation error which doesn't reflect the original value i.e. HTML not allowed for ParameterName

However it only does this for String properties.

For none String data types the AttemptedValue is encoded before being reflected; applying HttpUtility.HtmlDecode or otherwise injecting your own HTML into validation messages and writing custom code to render HTML in any validation message, introduces a reflected XSS bug if you have any none string parameters with default validation.

Rather that disabling built in behaviour, given that you don't necessarily know where the message will be set in the future, you should write a custom ValidationSummary helper which aggregates ModelState errors and a collection of custom validation errors which you know contain HTML, and crucially that you know don't contain any user input.

Related