Posted on:
Categories: SharePoint
Description:

I've run into situations in the past where I needed to insert client-side code (such as javascript) into a page dynamically from server-side code. For example, on some custom pages it is useful to add javascript to be called on page load, but many times the client side code needs data that is easily accessible server-side. In the most recent case, I was deploying a custom solution into an environment that I had no control over, and I needed to include JQuery and some custom javascript functions in the header, so that I could run some custom client-side code on certain pages. Since I did not have access or control over the master pages or application pages in the clients environment, this was a nice alternative.

To do this, I use a Delegate Control class, and using that control I target the AdditionalPageHead placeholder. In the server side code within that class, I inject the required client-side code.

The Setup

First, add an empty class to your SharePoint 2010 project in Visual Studio by selecting Class under the Code Templates in the Add New Item dialog. I named my user control ClientSideDelegateClass (I'll be using C# in this blog entry):

New Empty Element

Now we need to specify where to insert the new user control in the SharePoint master page. To do this, simply add another new item - this time, select Empty Element (again, under the SharePoint 2010 Templates in the Add New Item dialog). I called my element ClientSideDelegateCtlElement:

New User Control

You may optionally may also want to add some javascript files to a mapped layouts folder in your project, if you have large(r) functions you need to call.

If a feature was automatically created, ensure that it contains ClientSideDelegateCtlElement, and that it is web-scoped. If a feature was not automatically created, then add a new feature and make sure it's configured correctly (you can change the feature name and description as desired):

New Feature

The Code

Next we have to tell SharePoint where to put our newly created web control class (ClientSideDelegateClass). To do this, open up the empty element you created, and insert the following Control element inside the empty Elements tag. However, you will need to change the ControlAssembly and the ControlClass (both lines are highlighted in the below code snip-it) to correspond with your project. And, if you're like me, you'll want an easy way of finding out your assembly's PublicKeyToken...so if you haven't seen this already, check this msdn blog article out.

<Control Id="AdditionalPageHead" 
ControlAssembly="ClientSideSample, 
Version=1.0.0.0, 
Culture=neutral, 
PublicKeyToken=0f1ad6f8348c61d0" 
ControlClass="ClientSideSample.ClientSideDelegateClass"/>

The last thing you need to do with the element (and I always forget to do this) is register the control as a safe control. You can do this by selecting the element, and adding the control to the Safe Control Entries property collection in the properties window:

Safe Control Settings

NOTE: You may have to modify the Namespace, as I noticed in my environment by default the namespace was not correct.

Ok, now we just have to add the code to our class to inject the client-side code! Open ClientSideDelegateClass.cs, and you will need to add some code (see below):

public class ClientSideDelegateClass : System.Web.UI.WebControls.WebControl
{
 protected override void OnLoad(EventArgs e)
 {
  base.OnLoad(e);
 }

 protected override void CreateChildControls()
 {
  base.CreateChildControls();

  //inject required client side code here 
  this.Page.ClientScript.RegisterClientScriptInclude(
   "jquery181", 
   "//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js");
  this.Page.ClientScript.RegisterClientScriptBlock(
   this.GetType(), 
   "CustomPageLoadFn", 
   @" function OnCustomPageLoad() 
    { 
     alert('hello world!'); 
     $('body').css('background-color', 'aqua'); 
    } ", 
   true);
  this.Page.ClientScript.RegisterClientScriptBlock(
   this.GetType(), 
   "HelloWorldStartup", 
   " _spBodyOnLoadFunctionNames.push('OnCustomPageLoad'); ", 
   true);
 }
}

Now deploy the solution to any SharePoint site, and you should see a "Hello World!" messagebox, followed by the background colour changing. And notice that the background color was changed using JQuery, so if the background colour changed, then JQuery has been successfully included as well!

If you have any comments/questions/issues, please feel free to leave a comment on this page and I'll try and respond.