Johan Alkstål
Johan Alkstål

Reputation: 5347

MVC3 Razor removes script tags from HtmlString

I have a method that adds javascript to the end of partial views if it's an ajax request. My problem though is that when the script is returned, the script tags have been removed and the function I want to execute is written in plain text.

if (httpContext.Request.IsAjaxRequest())
        {
            script = "MyNamespace.globals.initFunctions.push(function() { " + script + " });";
            return new HtmlString(@"<script type=""text/javascript"">" + script + "</script>");
        }

So, instead of getting the desired result of

<script type="text/javascript">MyNamespace.globals.initFunctions.push(function() { MyNamespace.init(); });</script>

I get MyNamespace.globals.initFunctions.push(function() { MyNamespace.init(); }); in plain text.

What could be the reason?

Edit:

Trying it with Html.Raw() did not help. While the script string does contain the script tags, they are still removed when rendered.

    @{
    string script = ViewUtilities.AddScript("MyNamespace.init();", this.ViewContext.HttpContext);
}

    @Html.Raw(script);

Edit 2:

Now I've tried writing it all in the view like this,

<script type="text/javascript">
    MyNamespace.globals.initFunctions.push(function() { MyNamespace.init(); });
</script>

and it still removes the tags around the script and renders it as plain text. I don't know where to go from here...

When I exam the response with Firebug it looks fine but looking at the html it's not.

Upvotes: 2

Views: 2742

Answers (3)

counsellorben
counsellorben

Reputation: 10924

If you convert this to an HtmlHelper method, it will work. Change your ViewUtilities class as follows:

public static class ViewUtilities
{
    public static MvcHtmlString AddScript(this HtmlHelper htmlHelper, string script)
    {
        if (htmlHelper.ViewContext.HttpContext.Request.IsAjaxRequest())
            return new MvcHtmlString(@"<script type=""text/javascript"">" + script + "</script>");
        return new MvcHtmlString("");
    }
}

Then, in the web.config file in the Views folder (and in any Views folders in any Areas), add the following to the namespaces list in the <pages pageBaseType="System.Web.Mvc.WebViewPage"> element:

<add namespace="{namespace where ViewUtilities class is located}"/>

Finally, in your view:

@Html.AddScript("MyNamespace.init();")

Upvotes: 0

Eganr
Eganr

Reputation: 670

The HTML is being encoded which happens auto-magically with ASP.NET MVC.

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

Upvotes: 2

Chris Marisic
Chris Marisic

Reputation: 33098

You want to use @Html.Raw(whatever function you call)

I think you also probably want to return return MvcHtmlString.Create(fullscript);

Upvotes: 1

Related Questions