How to add a css reference within a server control?
.net, asp.net, c#, css
Solution
You need to follow the below steps to add the css/javascript/image in the web control itself.
Modify the AssemblyInfo.cs file, to add the web resource
[assembly: System.Web.UI.WebResource("CustomControls.Styles.GridStyles.css", "text/css"), PerformSubstitution = true)]
Adding the required files(css/javascript/images) to the custom server control solution. Note that we can add folders in the solution and just add separate it using '.'(dot)
More importantly, we should change the BuildAction Property from Content to Embedded Resource of the newly added css/javascript/image files.
Further we should load the stored resources from the DLL. Best event for this would be OnPreRender Below is the sample code rendering css
protected override void OnPreRender(EventArgs e)
{
bool linkIncluded = false;
foreach (Control c in Page.Header.Controls)
{
if (c.ID == "GridStyle")
{
linkIncluded = true;
}
}
if (!linkIncluded)
{
HtmlGenericControl csslink = new HtmlGenericControl("link");
csslink.ID = "GridStyle";
csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl(this.GetType(), "CustomControls.Styles.GridStyles.css"));
csslink.Attributes.Add("type", "text/css");
csslink.Attributes.Add("rel", "stylesheet");
Page.Header.Controls.Add(csslink);
}
}
Similarly for Adding javascript
protected override void OnPreRender(EventArgs e)
{
string resourceName = "CustomControls.GridViewScript.js";
ClientScriptManager cs = this.Page.ClientScript;
cs.RegisterClientScriptResource(this.GetType(), resourceName);
}
Similarly using the Added Image in CSS file. Use the below code
background: url('<%=WebResource("CustomControls.Styles.Cross.png")%>') no-repeat 95% 50%;
Thanks.
Problem
I've built a custom server control that uses custom CSS. The problem that I have is that I have to set a reference to the css file on each page I use the control. Can I set this reference inside the control ? So that I could just add the control and not worry about the reference.