Monday 26 September 2011

Asp.Net: Embed CSS in server control's assembly.

Question:
How to embed a CSS file in a server control assembly?
How to access style information (CSS) from a server control assembly?


Answer:
The style sheet file (CSS) must be an embedded resource. (right-click on the file and set Build Action to Embedded Resource.)

Follow these steps:
  1. Register a WebResource for the CSS file in the AssemblyInfo.cs
    ...
    [assembly: System.Web.UI.WebResource("MyControlStyle.css", "text/css")];
    ...
    
  2. Add Stylesheet include to the header of the page
    string styleLink= "<link rel='stylesheet' text='text/css' href='{0}' />";
    string location = Page.ClientScript.GetWebResourceUrl(this.GetType(), "MyControlStyle.css");
    LiteralControl styleInclude = new LiteralControl(String.Format(styleLink, location));
    ((HtmlControls.HtmlHead) Page.Header).Controls.Add(styleInclude );
    
    If you like the AjaxControlToolkit, you can have the second step in one line. (Include the AjaxControlToolkit.dll and namespace).
    Then add the ClientCssResource attribute to your main control class.
    ...
    [ClientCssResource("MyNameSpace.MyFolder.MyControlStyle.css")]
    ...
    
    In the Prerender event handler call the RegisterCssReference method of the static class ScriptObjectBuilder which is part of the AjaxControlToolkit
    ...
    ScriptObjectBuilder.RegisterCssReferences(this);
    ...
    
All resources embedded within an assembly will be included into the client page through a WebResource.axd request with a funny looking URL. But that should be transparent to you.

No comments: