Add ScriptManager to Page Programmatically?

2019-01-21 09:27发布

I am developing a WebPart (it will be used in a SharePoint environment, although it does not use the Object Model) that I want to expose AJAX functionality in. Because of the nature of the environment, Adding the Script Manager directly to the page is not an option, and so must be added programmatically. I have attempted to add the ScriptManager control to the page in my webpart code.

protected override void CreateChildControls()
{
    if (ScriptManager.GetCurrent(Page) == null)
    {
        ScriptManager sMgr = new ScriptManager();
        // Ensure the ScriptManager is the first control.
        Page.Form.Controls.AddAt(0, sMgr); 
    }
}

However, when this code is executed, I get the following error message:

"The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases."

Is there another way to add the ScriptManager to the page from a WebPart, or am I going to have to just add the ScriptManager to each page (or master page) that will use the WebPart?

7条回答
时光不老,我们不散
2楼-- · 2019-01-21 10:17

I had the same basic issue the rest of you had. I was creating a custom ascx control and wanted to be able to not worry about whether or not the calling page had the scriptmanager declared. I got around the issues by adding the following to the ascx contorl itself.

to the ascx page -

<asp:PlaceHolder runat="server" ID="phScriptManager"></asp:PlaceHolder>

in the update panel itself - oninit="updatePanel1_Init"

to the ascx.cs file -

protected void updatePanel1_Init(object sender, EventArgs e)
{
     if (ScriptManager.GetCurrent(this.Page) == null)
     {
         ScriptManager sManager = new ScriptManager();
         sManager.ID = "sManager_" + DateTime.Now.Ticks;
         phScriptManager.Controls.AddAt(0, sManager);
     }
}

Thank you to everyone else in this thread who got me started.

查看更多
登录 后发表回答