使用LoadControl方法动态加载UserControl(类型,对象[])

abj*_*hat 20 c# asp.net

我试图通过页面方法返回用户/服务器控件的html表示.当我调用带有虚拟路径到用户控件的重载时,它工作,但是当我尝试调用带有类型的重载时,它不起作用.示例代码如下.有什么建议?

[WebMethod]
public static string LoadAlternates(string productId, string pnlId)
{
    object[] parameters = new object[] { pnlId, productId };
    return ControlAsString(typeof(PopupControl), parameters);
}

private static string ControlAsString(Type controlType, object[] parameters)
{
    Page page = new Page();
    UserControl controlToLoad;
    /*
     *calling load control with the type results in the 
     *stringwriter returning an empty string
    */

    controlToLoad = page.LoadControl(controlType, parameters) as UserControl;
    /*
     *However, calling LoadControl with the following overload
     *gives the correct result, ie the string rep. of the control.
    */
     controlToLoad = page.LoadControl(@"~/RepeaterSamples/PopupControl.ascx") as UserControl;

    //some more code, then this... 
    page.Controls.Add(controlToLoad);

    StringWriter sw = new StringWriter();
    HttpContext.Current.Server.Execute(page, sw, false);
    return sw.ToString();
}
Run Code Online (Sandbox Code Playgroud)

有什么想法为什么这个StringWriter会返回一个空字符串?我应该指出,无论选择何种方法调用LoadControl,所有"页面"生命周期都能正确执行.

想添加 - 我必须使用LoadControl(Type, object[])过载.:-(

lom*_*axx 25

LoadControlMSDN页面上,底部有这样的评论:

描述
使用Page.LoadControl(Type,Object [])加载用户控件的页面似乎不会在ascx文件中创建其子项.使用Page.LoadControl(String)按预期工作.

评论
感谢您提交此问题.我们正在调查并在我们获得更多信息时提供最新状态.

- 网站平台和工具团队
由Microsoft于2005年6月8日上午11:08发布
这是因为"TestUC"类型实际上是部分类使用的基类型,它不包含正确的代码实例化TextBox1引用,它实际上是在派生类型中定义的.有两种解决方法:1.使用LoadControl("TestControl.ascx"),对于所有实际情况,它的行为与LoadControl(类型)完全相同,但它实例化派生类型,它知道如何实例化TextBox1.2.使用单个文件页面并将<%@ Reference%>指令添加到页面以引用用户控件,并为ascx页面指定类名.然后使用LoadControl(类型)是安全的

感谢您报告此问题.
网络平台和工具团队.微软于2005年6月14日下午6:31发布


Ste*_*ins 6

该重载实例化基类,但不实例化其上的任何控件,因此它不起作用.

如果你感兴趣,我做了一篇关于传递参数的解决方法的快速博客文章.