Search code examples
javascriptjqueryasp.net-mvcasp.net-mvc-3mvchtmlstring

Embed MvcHtmlString containing <script> with Javascript


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?


Solution

  • 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.