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

 

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.

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP since 2007. In addition, he's a multi-course video author at Pluralsight. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Follow

Get every new post delivered to your Inbox

Join other followers: