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 < and >.
<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:
<script src='../../Scripts/DataOutEventHandling.js' type='text/javascript'/>
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);
}
精彩评论