Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

c# - Inline code in head tag - 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" />
question from:https://stackoverflow.com/questions/8104268/inline-code-in-head-tag-asp-net

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...