Search code examples
asp.netajaxuser-controlshtml-rendering

Getting a scriptmanager into a dynamically rendered page


We are rendering usercontrols dynamically like this:

public string RenderControl(string pathcontrol)
{
    string html;

    var page = new Page();
    var control = page.LoadControl(path);            
    page.Controls.Add(control);

    // do stuff to the control (give it some data to work on)

    using (var writer = new StringWriter())
    {
        HttpContext.Current.Server.Execute(page, writer, false);
        html = writer.ToString();
    }

    return html;
}

This lets us the same user controls when rendering pages normally as we do when rendering responses to ajax calls. However, when adding controls which themselves contain a scriptmanagerProxy we run into the problem that the newed up Page object doesn't contain either a ScriptManager or the HtmlForm in which the ScriptManager needs to run.

Is there any way around this?

Yours Andreas


Solution

  • As others have said you can add a ScriptManger dynamically easily enough [ Add ScriptManager to Page Programmatically? if your Page object is complete.

    Can you try using BuildManager.CreateInstanceFromVirtualPath() to create the Page object instead? You issue may be how you create that object. There's a bit more to creating a new page than newing up the Page object.

    Eg.

    Page page 
           = BuildManager.CreateInstanceFromVirtualPath("~/Test.aspx", typeof(Page))
    

    See also http://www.west-wind.com/weblog/posts/120530.aspx for a little more background.