Thursday, May 5, 2011

How to add CSS and JavaScript in SharePoint Web Parts

While creating a web part I had to use some JavaScript and CSS. There are definitely other ways of doing this, I am just sharing the way I did it.

As you all know CSS is used for the look and feel. I had kept the CSS and JS files under the 12 hive folder structure. See below the folder structure of my solution.
image

In this example the name of the CSS file is Style.css, while deploying this, the files would be deployed inside 12 hive àLayouts folder. The basic objective is to refer this CSS file from inside the web part .cs file and render the look and feel. I have used HtmlLink to achieve this, first need to provide the path of the css file and then add to the page header controls collection section, find below the code

////--CSS file for the webpart--------------------

HtmlLink link = new HtmlLink();
link.Href = "/_layouts/A/CSS/Style.css";
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
this.Page.Header.Controls.Add(link);

JavaScript file would also reside in the same folder structure in 12 hive, however while adding it in the code, used the Client script Manager

////-- Adding JavaScript file ----------

ClientScriptManager cs = Page.ClientScript;

if (!cs.IsClientScriptIncludeRegistered("tab_javascript"))
{
     cs.RegisterClientScriptInclude(this.GetType(), "tab_javascript", "/_layouts/A/Scripts/Script.js");
}

Please post a comment if you have other ways of doing this same thing… I'll be happy to hear.

HaPpY CoDiNg... (Aurum)

No comments:

Post a Comment