Embed MvcHtmlString containing <script> with Javascript

3.6k views Asked by At

The following method of embedding some Html from a string in a <div> with Javascript (using some JQuery) works:

var div = $('#someId');
var testHtml = '<script></script><div>dummy Content</div>';
div.html(testHtml);

The Html code gets embedded and displayed in the div. If I put some alert('Test')-statement in the <script> tags, the alert would show up.

What also works is this:

<div id="someId">@MvcHtmlString.Create("<script></script><div>dummy Content</div>")</div>

However I need to pass a MvcHtmlString to a javascript function and then embed this string with javascript.

This works if there is no javascript code inside the string:

var div = $('#someId');
var inputItem = '@MvcHtmlString.Create("<div>dummy Content</div>")';
div.html(inputItem);

However if there is javascript content inside the string, the <script>-part does not get embedded and the content doesn't get displayed properly.

So this doesn't work properly:

var div = $('#someId');
var inputItem = '@MvcHtmlString.Create("<script></script><div>dummy Content</div>")';
div.html(inputItem);

Can someone explain why this doesn't work? Is there a simple trick to it?

3

There are 3 answers

0
nemesv On BEST ANSWER

I don't know in which browser you've tested (I've tested in IE8 and Chrome22) but your original example is also not working:

var div = $('#someId');
var testHtml = '<script></script><div>dummy Content</div>';
div.html(testHtml);

Check this JSFiddle

Because you cannot have "</script>" inside a JS string because the browsers interpreat it as the closing <script> tag. See this SO question: Script tag in JavaScript string

So the solution is the same for you so don't have directly the </script> inside the string:

<script type="text/javascript">
    var div = $('#someId');
    var testHtml = '@MvcHtmlString.Create("<script>alert(\"test\");</sc' + 'ript><div>dummy Content</div>")';
    div.html(testHtml);
</script>

You can also chek this in action in this JSFiddle.

0
A. Wolff On

Adding a fake attribute type to script tag other than " text/javascript" escape content. Ex:

var inputItem = '@MvcHtmlString.Create("<script type="text"></script><div>dummy Content</div>")';

Remove later this attribute could make the trick. But as i dont have idea how works MvcHtmlString, im really not sure it can be a solution here.

3
chridam On

The MvcHtmlString.Create method creates HTML that is encoded and strips HTML script tags.

Use @Html.Raw("htmlstring") to give you the raw HTML value of the string without stripping the tags.

var div = $('#someId');
var inputItem = '@Html.Raw("<script></script><div>dummy Content</div>")';
div.html(inputItem);