Back to Insights

Calling the Rating Service using jQuery in SharePoint 2010 Part 2 of 2

In Part 1 of this post, we looked at how to create a jQuery plugin to communicate with the Rating web service in SharePoint 2010. Here we'll look at how to register the scripts in our SharePoint site.

Registering the Script

In order for our custom jQuery plugin to work we need to get the script registered on our pages, to do this we use a delegate control in a SharePoint Module that is included in a SharePoint feature and activated when deployed. These delegate controls are fired as part of the page life cycle.

To do this, follow these steps:

  1. Add a new user control to your solution under the ControlTemplates mapped folder called RatingControlDelegate.ascx
  2. On the pre-render method of the control, register the client script as shown below
  3. Ensure that you hvae the RatingControl.js, jQuery and jQuery JSON script files in a folder in the Templates mapped folder (we put ours in Templates/Layouts/Common/Scripts for the jQuery and jQuery JSON scripts and Templates/Layouts/RatingControl for the RatingControl.js file)
  4. Ensure that the Template folder is included in your Package so that it is deployed when deploying your SharePoint Solution
  5. Create a New Module called RatingControlDelegate in your solution, and make sure the Elements file looks as follows:
<elements xmlns="http://schemas.microsoft.com/sharepoint/"> <control id="AdditionalPageHead" sequence="90" controlsrc="~/_ControlTemplates/RatingControlDelegate.ascx"> </control></elements> 

Your RatingContol should look like this:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;

namespace CustomRating.SharePoint.Controls
{
    public partial class RatingControlDelegate : UserControl
    {
        const string scriptKey = "RatingControl";
        const string scriptFile = "/_layouts/RatingControl/RatingControl.js";
        const string JQueryScriptFile = "/_layouts/Common/scripts/jquery-1.3.2.min.js";
        const string JQueryJSONScriptFile =  "/_layouts/Common/scripts/jquery.json-2.2.min.js";

        private string relativeUrl = (SPContext.Current.Site.RootWeb.ServerRelativeUrl == @"/" ? "" : SPContext.Current.Site.RootWeb.ServerRelativeUrl);

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            RegisterClientScriptInclude(this, "JQueryScript", JQueryScriptFile);
            RegisterClientScriptInclude(this, "JQueryJSONScript", JQueryJSONScriptFile);
            RegisterClientScriptInclude(this, scriptKey, string.Format("{0}{1}", relativeUrl, scriptFile));

        
            StringBuilder initScript = new StringBuilder("$(document).ready(function() {{");
            initScript.AppendLine("$('.ms-blogpostdatecol').RatingControl({{");
            initScript.AppendLine("CurrentUser:'{0}'");
            initScript.AppendLine("}});");
            initScript.AppendLine("}});");

            // register inline script block
            RegisterStartupScript(
                this, scriptKey, string.Format(initScript.ToString(), HttpContext.Current.User.Identity.Name.Replace("\\", "\\\\"))
                );

        }
        
         /// <summary>
	/// Checks if the specified JavaScript library is already registered and registers the script library
	/// </summary>
	/// The web part instance invoking this method.
	/// The key of the client script to register.
	/// The URL of client-side script include to register.
	private void RegisterClientScriptInclude(Control control, string scriptKey, string scriptUrl)
	{
	    ClientScriptManager csMgr = control.Page.ClientScript;

	    // register library if not already registered
	    if (!csMgr.IsClientScriptIncludeRegistered(scriptKey))
	    {
		csMgr.RegisterClientScriptInclude(scriptKey, scriptUrl);
	    }

	}


	/// <summary>
	/// Registers an unique instance of an inline script block
	/// </summary>
	/// The web part instance invoking this method.
	/// The key of the startup script to register.
	/// The startup script literal to register.
	private void RegisterStartupScript(Control control, string key, string script)
	{
	    RegisterStartupScript(control, key, script, true);
        }
        
        /// <summary>
	/// Registers an unique instance of an inline script block
	/// </summary>
	/// The web part instance invoking this method.
	/// The key of the startup script to register.
	/// The startup script literal to register.
	/// A Boolean value indicating whether to add script tags.
	private void RegisterStartupScript(Control control, string key, string script, Boolean addScriptTags)
	{
	    ClientScriptManager csMgr = control.Page.ClientScript;

	    // create unique key for inline script block
	    string initScriptKey = string.Format("{0}{1}", key, control.ClientID);

	    // register inline script block
	    if (!csMgr.IsClientScriptIncludeRegistered(control.GetType(), initScriptKey))
	    {
		csMgr.RegisterStartupScript(control.GetType(), initScriptKey, script, addScriptTags);
	    }
        }
    }
}

The above registers the scripts we need, and passes in the current user's username (CurrentUser) in the opts object to our jQuery plugin.

If you now deploy this solution and activate your feature, any page that contains the target HTML will be setup to allow an Up / Down voting. You will need to supply the icons and CSS to style your buttons.

Share