Thursday, February 26, 2009

Dynamically add a ScriptManager in a WebPart

I've been working on creating a web part that populates a ASP.NET Ajax ReorderList with SharePoint list content, allowing you to reorder based on a column. Since all ASP.Net AJAX components require a ScriptManager you need to either add one to the MasterPage or do it dynamically. I chose to do it dynamically so only the pages that had ASP.Net Ajax components would have it (making the pages a little less bloated).

To get a ScriptManager to dynamically add for your web part, add a ScriptManager declaration to your class:

ScriptManager _scriptManager;

then add this code to your CreateChildControls method:

if(_scriptManger == null)
{
//first check to see if there is a ScriptManager loaded on the page already
_scriptManager = ScriptManager.GetCurrent(this.Page);
if(_scriptManager == null)
{
//since there wasn't one on the page, we create a new one and add it to the controls collection
_scriptManager = new ScriptManager();
this.Controls.Add(_scriptManager);
}
}

No comments: