开发者

In ASP.NET Webforms, how do get my control to work in a link tag's href attribute?

I have a situation where I need to dynamically load a URL prefix.

I wrote a quick control to handle this and it works for the following instance:

<script type="text/javascript" src='<gbn:AdminPath runat="server" id="Id1" />Rest/Of/Path.js'></script>

But the following case (on the same aspx page) does not work:

<link rel="stylesheet" href='<gbn:AdminPath runat="server" id="Id2" />/css/styles.css'>

This shows up in the browser as:

<link rel="stylesheet" href="&lt;gbn:AdminPath runat=&quot;server&quot; id=&quot;Id2&quot; />/css/styles.css" />

I'v开发者_JAVA技巧e tried various things, but I can't seem to get the tags working. Any suggestions?

Thanks


The problem here is that it treats <link> elements in the <head> section like they are server controls. It does this, I believe, so that you can use app-relative urls (eg "~/myfolder/file.css") and have them resolved for you. It does not give this same treatment to <script> tags, though.

Since they are treated as server controls, you cannot mix inline script and string literals in a property value or it all gets treated as a literal (as you discovered).

To get around this, you have several options, one of which TheGeekYouNeed outline above.

If you still want to do it inline with a public method, you can, but you have to build the whole property value in your code like the following:

<link rel="stylesheet" href='<%= string.Format("{0}/css/styles.css", GetAdminPath() %>' type="text/css" />


Add the in the code behind

example:

// Define an HtmlLink control.
HtmlLink myHtmlLink = new HtmlLink();
myHtmlLink.Href = GetAdminPath() + "/pathtocss.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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜