[ZT] Best practices and common errors when adding a ScriptManager programmatically from a WebPart
Goal of this post This post aims at providing the most flexible and convenient way to make sure that a valid ScriptManager is available on page when you develop WebParts dealing with AJAX for ASP.net or Silverlight controls. Problematic overview ScriptManager is the key object making Silverlight and AJAX for ASP.net controls run on your ASP.net page. This non-visual control basically aims at loading JS scripts relevant for those technologies. Referring to MS documentation, it must appear as the first control in page controls tree in order to be available for any control requiring AJAX support. A ScriptManager can be embedded either from markup code of the hosting page, or programmatically during page lifecycle. So let’s imagine you are developing a WebPart embedding a Silverlight application. You want to redistribute this WebPart but you don’t want users to modify anything in their SharePoint portal to make it run. Basically, in your code, you will try to see if a ScriptManager is present on the page and if no you will add it on the fly. Then you have to face several issues:
Solution First, you need to add a new ScriptManager as the first control in the page form. Before adding anything, you have to ensure that no ScriptManager is already present on the page. if (Page != null && ScriptManager.GetCurrent(Page) == null) Then you need to determine where to place this code to be compliant with requirements evoked at question #3. The most reliable answer is to override the OnInit event of your WebPart and paste your code there protected override void OnInit(EventArgs e) An alternative approach could be to attach a handler to the page LoadComplete event, but it gives no gain to the previous solution. Common errors I’ve listed below some common mistakes and the corresponding errors when trying to answer to questions above.
Published on the 1/7/2009 6:37 PM by Olivier METRAL | Categories: AJAX ; Silverlight ; Web parts ; Best practices | Permanent link | Send this post by email | Comments (0) |