我试图通过页面方法返回用户/服务器控件的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[])
重载。 :(