views:

45

answers:

2

On Page_Load() in the codebehind, I'd like to enumerate all the <link> tags. The purpose being I want want to add a <link> to a CSS file if it isn't specified in the Page's markup.

How can I do this?

I'm thinking I should be able to use LINQ on the collection of elements in the header, no?

Here's my pseudocode:

var pageAlreadyContainsCssLink = false;

foreach(var control in this.Header.Controls) {
    if (control.TagName == "link" &&
        control.Attributes["href"] == "my_css_file.css") {
        pageAlreadyContainsCssLink = true;
        break;
    }
}

if (pageAlreadyContainsCssLink) {
    // Don't add <link> element
    return;
}

// Add the <link> to the CSS

this.AddCssLink(...);
A: 

Yes, your code should work. However, this situation should be managed at the root, by preventing it from happening so you will not need to code something 'just in case' to deal with it.

Your loop checked for the occurance of the css link, and if it exists then exit. What if there are 2 or more occurance? Do you want to remove the duplicate(s)?

I would suggest using one or combination of the followings:

  1. Masterpage (Single place for you to manage css files)
  2. Theme (All css files are linked automatically ONCE per page request)
  3. Code standandisation
  4. Single custom control within the header for all pages (need to make sure item 3 is in place)

1 and 2 is not applicable to ASP.NET 1.x, 3 and 4 applies to all.

o.k.w
+1  A: 

The solution is to enumerate the Controls collection as HtmlGeneric controls:

    foreach(HtmlControl control in this.Header.Controls)
    {
        if (control is HtmlLink &&  control.Attributes["href"] == this.CssFileLinkHref)
        {
            pageAlreadyContainsCssLink = true;
            break;
        }
    }
JamesBrownIsDead