1

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(...);
1
  • Your pseudo code is just fine. Commented Nov 28, 2009 at 0:29

2 Answers 2

1

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;
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.