Search code examples
htmlasp.net-mvc-3knockout.jshtml-entitieshtml-encode

How to display both single and double quotes in textbox or textarea


In the database, the data string has both single and double quotes in them.

Data string.

A'B"C

When it's displayed in a textbox or textarea, it's automatically encoded to html entities.

Code in MVC view, vm is the object binded with knockout.

vm.field1('@Model.field1');

Rendered HTML.

A'B"C

How do I make both of them display as single and double quotes again?

I tried to encode double quotes to ":

vm.field1("Html.Raw(Model.field1.Replace("\"", """))");

But that gave me:

A'B"C


Solution

  • I figured it out. I had to escape double or single quotes.

    escape single quotes:

    vm.field1('@Html.Raw(Model.field1.Replace("'", "\\\'"))');

    or escape double quotes:

    vm.field1("@Html.Raw(Model.field1.Replace("\"", "\\\""))")

    Update

    I found that there is security problem with my original solution. If the input is A'B'C</SCRIPT>, it'll break the javascript on the page. To resolve that, I HTML encode everything except single and double quotes.

    vm.field1('Html.Raw(Html.Encode(Model.field1).Replace("&#39", "\\\'").Replace("&quot;", "\""))');
    

    Update 2

    I found the AntiXss library has some tools for this and I found this will be even better.

    public static class StringExtensions
    {
        public static string ToQuotedJsString(this string s)
        {
            return Micorosoft.Security.Application.Encoder.JavaScriptEncode(s, true);
        }
    }
    

    then in the View:

    vm.field1(@Html.Raw(Model.field1.ToQuotedJsString()));