Extending WebForms Page class for registering stylesheet include

Extension method which enables registering stylesheet file reference

I recently started working on an Umbraco package for GoogleMap manipulation. Since initial version of package is planned only for Umbraco 6 I decided to use WebuserControl for creating a package custom datatype.

It means that for one document type I might have multiple control instances on the page.

Since control has some script and style includes, I needed to ensure that scripts and stylesheets are referenced only once regardless of the number of controls on a page.

This is already built-in for scripts with Page.ClientScript.RegisterClientScriptInclude. However this functionality does not exist for stylesheet.

Therefore, after some Google-ing and different approaches I found the way to do it.

The whole logic is in adding links to a page header with specific id. The same way you use key for registering a script on a page.

Just to make it more easier for using, I wrote it as an extension methods.

public static bool RegisterStyleSheetInclude(this System.Web.UI.Page page,string key, string styleSheetFilePath)
styleSheetFilePath = page.ResolveClientUrl(styleSheetFilePath);
if (page != null)
System.Web.UI.HtmlControls.HtmlHead head = (System.Web.UI.HtmlControls.HtmlHead)page.Header;
bool isExistStyleSheet = false;
foreach (System.Web.UI.Control item in head.Controls)
if (item is System.Web.UI.HtmlControls.HtmlLink && item.ID==key)
isExistStyleSheet = true;
if (!isExistStyleSheet)
System.Web.UI.HtmlControls.HtmlLink link = new System.Web.UI.HtmlControls.HtmlLink();
link.Attributes.Add("href", page.ResolveClientUrl(styleSheetFilePath));
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
                return true;
            return false;

Script registering method RegisterClientScriptInclude is void method, but for registering stylesheet I decided to return whether stylesheet file reference is added or not, so I have a better insight what is the outcome of method invoke.


Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

About the author


Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus


read more


read more

Umbraco CMS

read more


read more

Comments for this article