Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the asp.net head control mangle link elements?

Suppose I have the following markup in a standard ASP.NET 2.0 web form:

<head runat="server">
    <title>My Snazzy Page</title>
    <link type="text/css" href="<%= PathUtilities.AssetPath %>/css/page.css" rel="stylesheet" />
    <script type="text/javascript" src="<%=PathUtilities.AssetPath %>/lib/jquery/1.4.2/jquery.min.js"></script>
</head>

What's odd is that this renders the <link> element literally, with the embedded code brackets, while it interpolates the output of the same code into the script tag. In other words, the browser sees this:

<head><title>My Snazzy Page

</title><link type="text/css" href="&lt;%= PathUtilities.AssetPath %>/css/page.css" rel="stylesheet" />
<script type="text/javascript" src="/rmt/lib/jquery/1.4.2/jquery.min.js"></script>
</head>

Obviously the problem disappears if I remove the runat="server" from the head element.

like image 540
Thomas H Avatar asked Feb 25 '26 22:02

Thomas H


1 Answers

Well what you're doing is (no offence) a bit silly, that is - having a <head> server-side element, with a nested <link> client-side element with server-side href attribute

You are dynamically rendering the href value from server code anyway, so a better solution would be to dynamically render the link tag from the server altogether.

Example (code-behind of page)

// Define an HtmlLink control.
HtmlLink myHtmlLink = new HtmlLink();
myHtmlLink.Href = "/css/page.css";
myHtmlLink.Attributes.Add("rel", "stylesheet");
myHtmlLink.Attributes.Add("type", "text/css");

// Add the HtmlLink to the Head section of the page.
Page.Header.Controls.Add(myHtmlLink);

Your ASPX then becomes much neater:

<head runat="server">
    <title>My Snazzy Page</title>
    <!-- CSS/JS included dynamically -->
</head>
like image 172
RPM1984 Avatar answered Feb 27 '26 15:02

RPM1984