Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline code in head tag - ASP.NET

Tags:

c#

asp.net

Is it possible to do something like this in a head tag, of master page, which has runatserver:

 <link rel="Stylesheet" type="text/css" href='<%=Config.ResourcesDomain %>/images/style.css' /> 

This is not working, as it produces this kind of html:

<link rel="Stylesheet" type="text/css" href="&lt;%=Config.ResourcesDomain %>/images/style.css" /> 
like image 520
jekcom Avatar asked Nov 12 '11 11:11

jekcom


People also ask

What is inline code in asp net?

Inline Code refers to the code that is written inside an ASP.NET Web Page that has an extension of . aspx. It allows the code to be written along with the HTML source code using a <Script> tag.

What is use of <% %> in asp net?

<%$ %> is an ASP.NET Expression Builder. Used for runtime expression binding for control properties through the server tag attributes. Used with AppSettings , ConnectionStrings , or Resources (or your own custom extension, for example to use code-behind properties).

Is code that is embedded directly within the ASP NET page?

Embedded code blocks are supported in ASP.NET Web pages primarily to preserve backward compatibility with older ASP technology. In general, using embedded code blocks for complex programming logic is not a best practice, because when the code is mixed on the page with markup, it can be difficult to debug and maintain.


Video Answer


1 Answers

The reason the output is being rendered like so:

href="&lt;%=Config.ResourcesDomain %>/images/style.css" 

Is because ASP.NET is treating the link as an HtmlLink control, and rendering the contents of the href attribute as a literal.

This is a strange quirk of marking the head section as a server control, where certain elements are treated as server controls (even without being marked explicitly with the runat="server" attribute).

Removing the quotations around the href attribute resolves the issue:

href=<%= Config.ResourcesDomain %>/images/style.css 

Doing so stops the link element being treated as a server control, thus executing the code block and rendering the correct URL.

However, the above writes the href value out without quotes. Using the following, will add the quotes to the link tag:

href=<%= String.Format("'{0}'", Config.ResourcesDomain) %>/images/style.css 

Hope this helps.

Edit

Strangely, if you use double quotes for the href attribute, and include double quotes within the code block this also resolves the issue:

href="<%= "" + Config.ResourcesDomain %>/images/style.css" 

However, none of the above are particularly elegant solutions, and setting the URL from the code behind is probably the way to go.

like image 70
jdavies Avatar answered Sep 23 '22 18:09

jdavies