【发布时间】:2009-01-16 13:40:18
【问题描述】:
我正在尝试通过页面方法返回用户/服务器控件的 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[]) 重载。 :-(
【问题讨论】: