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

我试图通过页面方法返回用户/服务器控件的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(); } 

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

想添加 – 我必须使用LoadControl(Type, object[])重载。 🙁

在LoadControl的MSDN页面上,底部有这样的评论:

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

评论
感谢您提交此问题。 我们正在调查,并会在有更多信息时提供最新状态。

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

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

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

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

如果你想完全呈现控件,一种方法是使用LoadControl实例化控件,然后暂时将其添加到另一个控件或页面本身的控件集合中。 这将初始化该控件的生命周期并导致引发所有正确的事件。 完成此操作后,您可以从中获取所呈现的HTML或其他任何内容。

是的,这是一个黑客,但它会在紧张情况下工作。