Creating a Web Part with Client-side Scripts (Anweshi Deverasetty)

Hi again, this is Anweshi Deverasetty with a new blog post. You might have read my recent blog post Working with SharePoint 2010 Themes. Next, I am going to talk to you about how we can embed and link client side scripts for Web parts in SharePoint 2010.

About creating client-side scripts for Web Parts

Scripts are blocks of code that are inserted into a Web page and are interpreted at run time. Just like a browser interprets HTML on a Web page to determine what to display, a browser also interprets scripts to determine what actions to take when an event occurs (for example, what happens when a user clicks a button on a Web page).

Client-side scripts run on the client as opposed to the server. After a Web page is downloaded to the client computer, if the browser has enabled scripts to run, all the client-side scripts will run in the browser. Although script languages are simpler than programming languages, scripts can add sophisticated logic to Web pages and increase interactivity.

You can implement client-side scripting in a Web Part in one of two ways.

  • Linking a script file to a Web Part
  • Embedding a script in a Web Part

Linking a script file to a Web Part

You can write script in a separate file and place the file on a server running SharePoint Server 2010. The first time the script file is referenced, the file is fetched from the server and placed in the browser's cache. Subsequent references to the script file only require the script to be fetched from the browser's cache.

Advantages

  • It is more efficient for different Web Parts and Web Part Pages to share script placed in a common script file because the script is only fetched from the server the first time it is referenced and subsequent references fetch the script from the browser's cache.
  • The benefit is more obvious if the script is long. In this case, the Web Parts that reference the script are not burdened with the overhead of the lengthy script, and the script is only fetched once from the server and subsequently loaded into the browser's cache.
  • Placing a complex script into a separate file is also organizationally more practical and easier to maintain than embedding the entire script in the Web Part class definition.

In SharePoint 2010,it’s rather easy to start SharePoint and JavaScript development. You have a predefined set of SharePoint templates which will make it easier. Follow the below steps.

  1. Create a script in a file called Hello.js, and add the following code that shows a message box that says “hello”.

     function Hello() {
        alert('Hello');
    }
    
  2. Open Visual Studio 2010 with administrator rights, select Visual Web Part Project from SharePoint 2010 Projects, and click OK.

  3. Specify the local site URL for debugging and select “Deploy as farm solution”.

  4. Open the VisualWebPart1.cs file.

  5. The VisualWebpart1 class is inherited from System.Web.UI.WebControls.WebParts.WebPart. Change the inherited class to Microsoft.SharePoint.WebPartPages.WebPart.

  6. Add a “Empty Element” project item named “JSScripts” from SharePoint 2010 templates. You can use Solution Explorer or the Project menu to add this project item template.

  7. Copy or move the Hello.js file to the JSScripts folder by using Windows Explorer.

  8. Next, add the existing Hello.JS file in to the “JSScripts” element.

  9. Select the properties for the Hello.JS file, and change the Deployment Type property to ClassResource. After you change this, the Deployment Location property changes to {ClassResourcePath}\VisualWebPartProject1\JSScripts\. The ClassResourcePath token basically maps to C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/wpresources/WebControlLibrary1/1.0.0.0__e59f6e1bd7abeada.

  10. Let’s change the deployment path as {ClassResourcePath}\JSScripts. This can be done by editing Path from Deployment Location property.

  11. When you build and deploy the solution, it gets deployed to wpresources folder. After deploying you can navigate to the JS using the following URL.

         https://serverURL/_wpresources/VisualWebPartProject1/
          1.0.0.0__e59f6e1bd7abeada/JSScripts/Hello.js
    
  12. You can determine this URL and GUID by navigating to the physical folder c:\program files\common files\microsoft shared\web server extensions\wpresources\visualwebpartproject1\1.0.0.0__xxxxxxxxxx

Now, let’s see how to link this JS file in the webpart. Open VisualWebPart1.cs file and add the following code.

  1. Specify a key for the script. The Page object uses this key to determine if the script has already been loaded onto the Web Part Page. Add the following lines to the Web Part object.

     private const string HelloFileName = "Hello.js";
    private const string HelloIncludeScriptKey = "myHelloIncludeScript";
    private const string IncludeScriptFormat = 
        @"<script language=""{0}"" src=""{1}{2}""></script>";
    
  2. Then add an event handler to the PreRender event that loads the script onto the page on prerendering.

     public VisualWebPart1()
    {
        this.PreRender += new EventHandler(VisualWebPart1_PreRender);
    }
    
  3. Then add the following code that creates a clientscriptmanager, which creates a client script block. The block is used to link a JS file to a Web part.

     private void VisualWebPart1_PreRender(object sender, System.EventArgs e)
    {
        ClientScriptManager cs = Page.ClientScript; 
    
        if (!cs.IsClientScriptBlockRegistered(HelloIncludeScriptKey))
        {
            String location = this.ClassResourcePath + "/JSScripts/";
    
            // Create the client script block.
            string includeScript =
            String.Format(IncludeScriptFormat, "javascript", location, HelloFileName);
            cs.RegisterClientScriptBlock(
                this.GetType(),
                HelloIncludeScriptKey, 
                includeScript);
        } 
    }
    

The Page.ISClientScriptBlockRegistered and Page.RegisterClientScriptBlock methods are obsolete in Sharepoint 2010. So, use ClientScriptManager class to call these methods.

Embedding script in a Web Part

You can explicitly specify your script in a Web Part and have the script loaded only once for all instances of the same Web Part on a Web Part Page. The IsClientScriptBlockRegistered method of the System.Web.UI.ClientScriptManager class can check if the script has been loaded for the same Web Part Page.

Advantages

  • Similar to linking to a script file, the script is loaded only once for all instance of the same Web Part on that Web Part Page.
  • For short scripts, clarity and convenience outweigh performance gains.
To Embed a script in a Web Part  

For example, let us suppose that you have a script function called ByeBye() that you would like to add to your Web Part, VisualWebPart1. Add the following code so that the script is loaded only once for all instances of the same Web Part on the Web Part Page.

 private void VisualWebPart1_PreRender(object sender, System.EventArgs e)
{
    ClientScriptManager cs = Page.ClientScript; 

    if (!cs.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey))
        cs.RegisterClientScriptBlock(
            this.GetType(),
            ByeByeIncludeScriptKey,
            EmbeddedScriptFormat);
}

Sample Web Part with client-side scripts

The following example shows how you can add two client-side scripts to a Web Part, VisualWebPart1 first by linking a separate script file to the Web Part, and then by embedding the script in the Web Part.

Here are the steps that you need to follow to create a visual Web part with client side scripts.

 //---------------------------------------------------------------------
// File : VisualWebPart1.cs
//
// Purpose :  Show an example of how to include client side script to your page.
//           1) Linking to a .js file
//           2) Added embedded script to the page.
//---------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Web.UI;

namespace VisualWebPartProject1.VisualWebPart1
{

    [ToolboxItemAttribute(false)]
    public class VisualWebPart1 : Microsoft.SharePoint.WebPartPages.WebPart
    {
        // Visual Studio  automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = 
            @"~/_CONTROLTEMPLATES/VisualWebPartProject1/
            VisualWebPart1/VisualWebPart1UserControl.ascx";

        // Used for the linked script file
        private const string HelloFileName = "Hello.js";
        private const string HelloIncludeScriptKey = "myHelloIncludeScript";
        private const string IncludeScriptFormat = 
            @"<script language=""{0}"" src=""{1}{2}""></script>";

        // Used for the embedded script
        private const string ByeByeIncludeScriptKey = "myByeByeIncludeScript";
        private const string EmbeddedScriptFormat =
            "<script language=javascript>function ByeBye(){alert('Bye Bye'); }</script> ";

        // Contructor
        public VisualWebPart1()
        {
            this.PreRender += new EventHandler(VisualWebPart1_PreRender);
        }

        // Client script registration event
        private void VisualWebPart1_PreRender(object sender, System.EventArgs e)
        {
            ClientScriptManager cs = Page.ClientScript; 

            if (!cs.IsClientScriptBlockRegistered(HelloIncludeScriptKey))
            {
                String location = this.ClassResourcePath + "/JSScripts/";

                // Create the client script block.
                string includeScript =
                String.Format(IncludeScriptFormat, "javascript", location, HelloFileName);
                cs.RegisterClientScriptBlock(
                    this.GetType(),
                    HelloIncludeScriptKey, 
                    includeScript);
            } 

            if (!cs.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey))
                cs.RegisterClientScriptBlock(
                    this.GetType(),
                    ByeByeIncludeScriptKey,
                    EmbeddedScriptFormat);
        }

        /// <summary>
        /// Render this Web Part to the output parameter specified.
        /// </summary>
        /// <param name="output">
        /// The HTML writer to write out to
        /// </param>
        protected override void Render(HtmlTextWriter output)
        {
            //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 calls a function that is embedded in the page
            output.Write(
                  "<br><br><input class='ms-SPButton'" +
                  " value=\'Say Bye Bye\' type=button onclick=\"ByeBye();\" >");
        }
         
        protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            Controls.Add(control);
        }
    }
}
To deploy this sample Web Part 

Deployment in SharePoint 2010 is very easy. You need to build the solution and use the deploy option. Once deployed you will see that the Hello.JS file gets deployed to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\wpresources\VisualWebPartProject1\1.0.0.0__e59f6e1bd7abeada\JSScripts.

To test this Web Part to the page

Follow the below procedure to add the Web part to a Web part page.

  1. Navigate to Site Settings, Galleries, and then select Web Parts.
  2. Click on New Document from Ribbon and select the newly deployed Web part ie., VisualwebPartProject1_VisualWebPart1.web part.
  3. Now navigate to Web Part Page and add this Web part.
  4. After the Web part is added, you will see 2 buttons “Hello” and “Say Bye Bye” .
  5. “Hello” button calls a JavaScript function which is available in Hello.js and the “Say Bye Bye” calls the embedded JavaScript function.

Conclusion

This topic explained how to create, embed, and link client side scripts for Web parts in SharePoint 2010. For more information, see https://msdn.microsoft.com/en-us/library/dd584169(office.11).aspx to know how this can be implemented in SharePoint 2003.