Nick
Nick

Reputation: 19664

How do I stop <%= from html encoding my script tags?

I am trying to add js dynamically to my view using a custom HTML Helper. The problem I am facing is that the the following server tag is encoding my < and > to &lt and &gt.

    <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    <%: Model.ProductName %>

    <%foreach (var script in Model.DynamicIncludes)
  {%>
      <%=Html.ScriptTag(Url.Content(script))%>
  <%} %>    

</asp:Content>

This is what my helper looks like:

 public static class ScriptHelper
    {
        public static string ScriptTag(this HtmlHelper helper, string path)
        {
            return string.Format("<script src='{0}' type='text/javascript'/>", path);
        }
    }

When I view the html source the script includes are being written to the reponse stream like so:

&lt;script src='../../Scripts/DataOutEventHandling.js' type='text/javascript'/&gt;

This application is written using the ASP.NET MVC 2.0

Upvotes: 0

Views: 641

Answers (3)

Nick
Nick

Reputation: 19664

For some reason the script tags were being nested. In my helper I added a closing tag rather than using a self closing script tag and it fixed the problem.

 public static string ScriptTag(this HtmlHelper helper, string path)
    {
        return string.Format("<script src='{0}' type='text/javascript'></script>", path);
    }

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038880

<%=Html.ScriptTag(Url.Content(script))%> will not encode. You probably use <%:Html.ScriptTag(Url.Content(script))%> which performs the HTML encoding.

Notice the difference between <%= and <%:.

Upvotes: 0

George Johnston
George Johnston

Reputation: 32258

Use Html.Raw around your formatted value. You can place this anywhere you find approprate. e.g.

<%=Html.Raw(Html.ScriptTag(Url.Content(script)))%>

http://msdn.microsoft.com/en-us/library/system.web.webpages.html.htmlhelper.raw(v=vs.99).aspx

Upvotes: 2

Related Questions