0

I'm attempting to add a ScriptManager control programmatically, but only if one doesn't exist on the page. I've found many examples for this that put the logic inside Page_Init, which makes sense (have since realized it doesn't make sense- see bottom edit), but I'm getting an exception before my Init method is ever hit.

protected void Page_Init(object sender, EventArgs e)
{
    if (ScriptManager.GetCurrent(Page) == null)
    {
        ScriptManager sMgr = new ScriptManager();
        Page.Form.Controls.AddAt(0, sMgr);
    }
}

This makes me think Sitecore is getting in the way somehow. Has anyone successfully done this using Sitecore?

Thanks.

EDIT: The exception I'm receiving is as follows: "The control with ID 'filtersUpdatePanel' requires a ScriptManager on the page. The ScriptManager must appear before any controls that need it."

EDIT^2: What was really going on here was that Page_Init is too late in the life cycle to attach a ScriptManager (in my case). With Init, all child events are fired first, then Page. The UpdatePanel's init didn't see a ScriptManager, so it threw an exception. Putting the ScriptManager logic in the UpdatePanel init solved the issue.

2
  • 2
    Could you post the exception? Commented Mar 7, 2012 at 21:20
  • There you go. That would help wouldn't it? Commented Mar 8, 2012 at 14:40

1 Answer 1

2

What I usually do is create a PlaceHolder control in my base layout. Then in my Page_Init (or in the Init of the control that requires the ScriptManager, like an UpdatePanel) I place the following code:

if (ScriptManager.GetCurrent(this.Page) == null)
{
    ScriptManager scriptManager = new ScriptManager
    {
        ID = String.Concat("ScriptManager", DateTime.Now.Date.Ticks),
        EnablePartialRendering = true,
        ScriptMode = ScriptMode.Release
    };

    var placeholder = this.Page.FindControl("PlaceHolderScriptManager") as PlaceHolder;

    if (placeholder != null)
    {
        placeholder.Controls.Add(scriptManager);
    }
}

I have modified it a little without testing, but it should work fine.

Sign up to request clarification or add additional context in comments.

1 Comment

See my edit for notes on this. Definitely helped me arrive at the answer! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.