Wednesday, July 27, 2011

Power of Delegate Control- What/Why/How

I get a lot of questions from junior developer as to why use a delegate control and how do you implement a delegate control?

A delegate control is a control that will be rendered. The key thing here is that at the run time it finds all controls with the same id and then adds to tree the control with lowest seq number. The delegate control is mainly added to Master Page that is tied to your site. If you view the Master Page's code you will find several delegate controls as those are added by SP.

Why use a delegate control?
You will choose to use a delegate control if you want to add some code that is rendered on every single page in your site. The alternative way is you would add a user control containing your code to every single page on your site. If you create new page, then you have to remember to add this user control. This is not the best approach and for this reason you create a delegate control and add it to Master Page and then it is rendered on every page that uses this MasterPage. You can have more than 1 delegate control of the same ID, but the delegate control with the lowest seq will get added to the tree to render.

How do you create a delegate control?
There are 2 things involved in a delegate control.
- Master Page
- User Control created using Visual Studio.

Steps required to create DC
1. Create a new Empty SharePoint 2010 Project.
2. Map it to ControlTemplate Folder.
3. Right Click on ControlTemplate Folder and add a User Control.
4. Add your code in the User Control.
5. Right click on the project and add a module. This will create Elements.XML file
6. In the elements.xml add this code:





7. Delete the feature that got created and then add a new feature with a more meaningful name with information.
8. Open your MasterPage that is beeing used by your Site and add code like this

at top around the GlobalNavigation control.
9. Deploy your code and test it.

No comments:

Post a Comment