JejuneWolf
JejuneWolf

Reputation: 79

Css link can't call the variable from behind code in asp.net?

I write it in aspx like this:

<link type="text/css" href='/theme<%=theme%>/top.css' rel="stylesheet" />

but result is this:

<link type="text/css" href="/theme&lt;%=theme%>/top.css" rel="stylesheet" />

surprising is that using in js is no problem.

Upvotes: 0

Views: 1102

Answers (2)

KV Prajapati
KV Prajapati

Reputation: 94645

You can't use expressions with <head runat="server"> instead you have to write following code in Page_Load event to insert <link/>

HtmlLink link = new HtmlLink();
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "Stylesheet");
link.Attributes.Add("href", "/theme" + theme + "/top.css");
Header.Controls.Add(link);

Upvotes: 0

aquinas
aquinas

Reputation: 23796

It's because your link is inside a <head> tag which is runat server. The head tag is "smart", in that when it sees a <link> tag it lets you actually use the application relative path syntax: ~/. So if you do (inside your head tag):

<link href="~/Content/Site.css" rel="stylesheet" />

You'll see it will actually work (that is, it will expand the tilde to the proper location of your site), even though nowhere did you say runat server. The downside of course is when you DON'T want it to do that. :) Probably the easiest solution is to just manually build the tag yourself like this:

<%= "<link type=\"text/css\" href='/theme" + theme + "/top.css' rel=\"stylesheet\" />" %>

Upvotes: 3

Related Questions