Safely Encoding Strings On ASP.NET MVC Razor Pages (sometimes)

Posted by Peter Kellner on April 05, 2014 · 3 mins read

 

Background

Sometimes, we want to let html tags come through our web pages from user defined content.  If for example, you have a workflow that requires approval before publishing, there are times when you want to let the author put through html, links, etc. 

Solution

In Visual Studio write a simple HtmlHelper method that allows for a flag you can pass through.  In my case, I have a database table with a boolean column “allowhtml”.  If this is set, then instead of using Html.Raw(…) I can use my own helper method, pass in the allowHtml value and if it is set true, then allow the not encoded Html to flow through.

Here is that helper method:

namespace WebAPI.Code.Helpers
{
    public static class SvccHtmlHelperExtension
    {
        public static MvcHtmlString SafeEncodeSvcc
            (this HtmlHelper helper, string inString, 
            bool? allowHtml = false)
        {
            string s =
                allowHtml.HasValue && allowHtml.Value
                    ? inString
                    : HttpUtility.HtmlEncode(inString);
            return new MvcHtmlString (s);
        }

Then, in the razor page (.cshtml)

<div class="sessionDescription" id="sessionDescription_@session.Id">
    <p>@Html.SafeEncodeSvcc(session.Description,session.AllowHtml)</p>
</div>

This way, the syntax is tight and I just use this instead of Html.Raw all the time.

Here is a good reference: http://www.dotnetperls.com/htmlencode-htmldecode

HTH’s.