开发者

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 hel开发者_运维百科per, 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


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


<%=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 <%:.


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);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜