Monday 26 December 2011

Delegate Control

SharePoint Delegate control is a mechanism that we can insert a code or control to the SharePoint Master page(and Page Layout) without touching any of code in the SharePoint Master page(and in Page Layout) and also it is a container type control which can holds child controls on it 

The Search bar is located at the top of all the pages in a site, and the master page uses a delegate control in a placeholder to determine what to render at runtime. Here is the markup for the delegate control:


<SharePoint:DelegateControl runat=”server” ControlId=”SamllSearchInputBox”/>

Note that the ControlId value determines what delegate control is needed to be added in the respective place.

Importance:
·         Using the delegate control a developer can customize the SharePoint site controls without editing the code master page (After inserting the Delegate).
·         Suppose if you want add a counter for no.of.vistors to the site. We created a control for displaying the total count in the master page. If we want to keep this control in the master page we need to edit that master page and add all the controls over here. At any time if any mistake happen then whole master page will be changed knowingly or unknowingly. To avoid this we have delegate controls.

AdditionalPageHead
Top most delegate control in the master page allows multiple controls. You can use this delegate to inject JavaScript, custom logic, etc. to the master page. You can specify a control which only has a code to do whatever you need in onLoad event.
<Control Id="AdditionalPageHead" Sequence="90"             
           ControlSrc="~/_CONTROLTEMPLATES/a/test1.ascx" />

<Control Id="AdditionalPageHead" Sequence="91"             
           ControlSrc="~/_CONTROLTEMPLATES/b/ test1.ascx" />
Sequence controls the order if more than one control



Scenario 1 (Creating Delegate Within Master Page Itself)

You can create new simple delegate within the master page itself.





Scenario 2 (Creating Custom delegate control using Visual Studio)
Steps:
1.       Open Visual Studio 2010 and create a new Empty SharePoint project.
2.       Map a new folder to the CONTROLTEMPLATES directory in the SharePoint root (the 14 hive).
3.       Add a new item visual web part and empty element like below image.


4.       Design the logic inside the Visual Web part or add an div element with sample text for testing  and finally edit the Element.xml file like below

<?xml version="1.0" encoding="utf-8"?>


<Control Id="MyControl" Sequence="20" ControlSrc="~/controltemplates/TestTemp.ascx" />

</Elements>
5.       Save the changes and deploy into the site.
6.       Now we created a delegate control and want to add it to our site. Now add the following code to our master page anywhere you want.

<SharePoint:DelegateControl ControlId=" MyControl " AllowMultipleControls="true" runat="server">
</SharePoint:DelegateControl>





No comments:

Post a Comment