Skip to content

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

Updated: at 02:12 PM



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. 


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">

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

Here is a good reference:


Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects