我试图通过页面方法返回用户/服务器控件的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[])过载。:-(
发布于 2009-01-16 13:47:03
在用于LoadControl的MSDN页面的底部有这样的评论:
描述 使用Page.LoadControl(Type,Object[])加载用户控件的页面似乎不创建添加到ascx文件中的子控件。使用Page.LoadControl(String)按预期工作。 评论 谢谢你提交这个问题。我们正在调查,当我们有更多的信息时,我们会提供最新的状态。 -The网络平台与工具团队 微软于2005年06月8日上午11时08分发帖 这是经过设计的,因为类型"TestUC“实际上是分部类使用的基本类型,它不包含实例化TextBox1引用的适当代码,而该引用实际上是在派生类型中定义的。有两个解决办法: 1.使用LoadControl("TestControl.ascx"),在所有实际操作中,这与LoadControl(类型)相同,但它实例化派生类型,后者知道如何实例化TextBox1。2.使用单个文件页并向页面添加<%@ Reference %>指令,以引用用户控件,并为ascx页分配一个类名。那么使用LoadControl(类型)是安全的 谢谢你报道这个问题。 Web平台和工具团队。微软于2005年6月14日下午6时31分发帖
发布于 2009-01-16 13:51:57
该重载实例化基类,但不实例化基类上的任何控件,因此无法工作。
如果您感兴趣的话,我为传递参数做了一个快速的博客帖子。
发布于 2009-01-16 15:00:59
如果希望完全呈现控件,一种方法是实例化控件,就像现在使用LoadControl一样,然后将其临时添加到另一个控件或页本身的控件集合中。这将初始化该控件的生命周期,并引发所有适当的事件。一旦您这样做了,那么您就可以从它得到呈现的HTML或任何您需要的东西。
是的,这是一个黑客,但它会在紧要关头工作。
https://stackoverflow.com/questions/450431
复制相似问题