2

I have a text &lt;script&gt;alert('injection');&lt;/script&gt; which I want to render as it is in the view which is rendered as jquery template in ASP MVC3 application. But &lt; is dsiplayed as <.

My jquery templates is below:

<script id="nameTemplate" type="text/x-jquery-tmpl">
    <p>${Name}</p>
</script>

How we can render it as plain text?

Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
user1999616
  • 61
  • 1
  • 9

2 Answers2

1

As hinted at by SpaceBison, your browser will decode HTML-encoded values and write them out as 'plain-text' HTML.

In order to write the value out encoded, you will effectively have to 'double-encode' the value, so when the browser decodes and renders it, it will still be encoded once.

If your value originally comes from an ASP.NET MVC model property, or similar (assuming this based on your tags), you can use HttpUtility.HtmlEncode in your server-side code, for example:

Model.Name = HttpUtility.HtmlEncode(Model.Name);

However, if you need to do this in the front-end, you can write a simple jQuery function to encode the value (shamelessly stolen from this answer):

function HtmlEncode(str) {
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

You can then do the following in your jQuery, before you add the item to your container:

Name = HtmlEncode(Name);

To see it in action: http://jsfiddle.net/Rb2VJ/1/

Community
  • 1
  • 1
Ant P
  • 24,820
  • 5
  • 68
  • 105
0

To get &amp; literally, use &amp;lt;

$(elem).text("&lt;"); will also display it as plain text.

$(elem).html("&amp;lt;"); for HTML.

http://jsfiddle.net/yCuZt/

SpaceBison
  • 3,704
  • 1
  • 30
  • 44
  • My problem is value of ${Name} is <script>alert('injection');</script>. I want to display as it is. But, when it is rendered as – user1999616 Mar 27 '13 at 10:23