Referring Embedded Javascript files and CSS from a Custom Blank WebPart in SharePoint 2013

Sathish Nadarajan
 
Solution Architect
August 14, 2013
 
Rate this article
 
Views
16316

Usually, we may write many lines of JavaScript and JQuery calls from our SitePages by using the Script Editor WebPart. If we want to edit the Scripts in the WebPart, we should have enough permission to Edit Page. If not, we may not be able to modify the scripts on the fly. Moreover, if any of the end user, does have permission to edit the page, he can Edit the script as well.

To avoid these things, Let us create a Blank WebPart. On the render of the WebPart, the JavaScript files will get rendered. To create a WebPart with JavaScript files, follow the steps.

1. Open the Visual Studio as Administrator.

2. Create an Empty SharePoint Solution.

clip_image001[4]

3. Select the SiteCollection and Choose Farm Solution on the next dialog.

clip_image003[7]

4. Add New Item.

clip_image005[4]

5. Add an Empty Element.

clip_image007[4]

6. The solution will look like below.

clip_image009[4]

7. On the Element, Add new Item.

clip_image011[4]

8. Select JavaScript file.

clip_image013[4]

9. Add a sample script on the file.

function Hello() {   alert('Entered By Button Click');  } 

10. Select the JavaScript file and change the Deployment Type into “ClassResource” on the Properties window. The reason for this is being explained on the later portion of the article.

clip_image015[4]

11. In the same manner Add two more empty elements and change the Deployment Type to ClassResource. One is for JQuery and one is for CSS.

12. Now, we are done with the JavaScript file. Let us add a web part to our solution.

clip_image017[4]

13. Now, add a visual WebPart Template.

clip_image019[4]

14. Our solution may contain 2 features added. One is for the JS file and the other one is for WebPart. Club those feature into one or keep it as two. I am leaving that to you.

15. By default, the WebPart will be inherited from System.Web.UI.WebControls.WebParts.WebPart. Instead inherit from Microsoft.SharePoint.WebPartPages.WebPart. Now your webpart.cs file should look like this. The render and pre-render code are self-explanatory and can be understood easily.

[ToolboxItemAttribute(false)]   public partial class Sathish : Microsoft.SharePoint.WebPartPages.WebPart   {   public Sathish()   {   using (SPMonitoredScope monitoredScope = new SPMonitoredScope("SampleScripts"))   {   //Adding a PreRender Event for this WebPart   this.PreRender += new EventHandler(Sathish_PreRender);   }   }     //On the PreRender, We are going to render the Javascript file.   private void Sathish_PreRender(object sender, System.EventArgs e)   {   using (SPMonitoredScope monitoredScope = new SPMonitoredScope("SampleScripts"))   {   try   {   //This class ULSLog is a custom class used for logging purpose.   ULSLog.LogDebug("Entered into PreRender - To Register JS File");   ClientScriptManager cs = Page.ClientScript;     //Includes the JQuery   string IncludeScript = string.Format(@"<scriptlanguage=""{0}"" src=""{1}{2}""></script>", "javascript", this.ClassResourcePath, "/JQuery/jquery-1.9.0.min.js");     cs.RegisterClientScriptBlock(this.GetType(), "JQueryIncludeKey", IncludeScript);     //Below lines will be UnCommented To Increate the Performance while Deploying - Sathish   //if (!cs.IsClientScriptBlockRegistered(IncludeScriptKey))   //{     //Includes our Javascript File   IncludeScript = String.Format(@"<script language=""{0}"" src=""{1}{2}""></script>", "javascript", this.ClassResourcePath, "/JavaScripts/MyJavascriptFile.js");   cs.RegisterClientScriptBlock(this.GetType(), "SampleScriptIncludeKey", IncludeScript);   //}   ULSLog.LogDebug("Rendered the JS-Scripts Successfully");   }   catch (Exception ex)   {   ULSLog.LogError(ex);   }   }   }         //Since CSS will be available only on the render Event of the WebPart, we are renderinig the CSS here.   protected override void Render(HtmlTextWriter output)   {   RenderCSS(output);     }     //CSS will be rendered.   private void RenderCSS(HtmlTextWriter output)   {   using (SPMonitoredScope monitoredScope = new SPMonitoredScope("SampleScripts"))   {     try   {   ULSLog.LogDebug("Entered into Render - To Render CSS");     string location = this.ClassResourcePath + "/CSS/MyCSS.css";   string strCSS = string.Format(@"<link rel=""stylesheet"" href=""{0}"" type=""text/css"" />", location);         output.Write(strCSS);     //The Below lines were used to Test the Scripts and CSS file, whether they were rendered on the screen or not.   ////Button which calls a function from the Included File .js   output.Write(   "<br><br><input class='ms-SPButton'" +   " value='Say Hello' type=button onclick="Hello();" >");     //Button which Render the CSS   output.Write(   "<br><br><input class='Mydiv'" +   " value='Say Hello Test' type=button onclick="Hello();" >");     base.Render(output);   ULSLog.LogDebug("Rendered the CSS Files Successfully");   }   catch (Exception ex)   {   ULSLog.LogError(ex);   }   }   }             protected override void OnInit(EventArgs e)   {     base.OnInit(e);   InitializeControl();     }   }

1. The highlighted ClassResource, is the reason, why we gave in the beginning. Once, we gave the Deployment Type as Class Resource, this can be accessed easily from our web Part instead of using the layouts or any other location. After we change this, the Deployment Location property changes to {ClassResourcePath}\VisualWebPartProject1\JavaScripts\. The ClassResourcePath token basically maps to C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/wpresources/WebControlLibrary1/1.0.0.0__e59f6e1bd7abeada.

16. The same is the reason to inherit the web part from Microsoft.SharePoint.WebPartPages.WebParts too.

Now, let us deploy the solution and you can see a WebPart listed on the WebPart gallery. Now, edit the page on which you want to render these scripts, and add this WebPart. This will do the magic. The Project solution has been attached with this article.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment