gpt4 book ai didi

c# - 使用 LoadControl 方法动态加载 UserControl (Type, object[])

转载 作者:IT王子 更新时间:2023-10-29 04:38:21 26 4
gpt4 key购买 nike

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

最佳答案

关于 MSDN page for LoadControl底部有这样的评论:

Description
A page that loads a user control using the Page.LoadControl(Type, Object[]) does not seem to create its children added in the ascx file. Using Page.LoadControl(String) works as expected.

Comments
Thank you for submitting this issue. We're investigating and will provide an update on status when we have more information.

-The Web Platform & Tools Team
Posted by Microsoft on 8/06/2005 at 11:08 AM
This is by-design since the type "TestUC" is actually the base type used by the partial class, it does not contain the proper code to instantiate TextBox1 reference, which is actually defined in the derived type. There are two workarounds: 1. Use LoadControl("TestControl.ascx"), for all practical, this behaves identically to LoadControl(type) but it instantiates the derived type, which knows how to instantiate TextBox1. 2. Use a single file page and adds <%@ Reference %> directive to the page to reference the user control, and assign a classname to the ascx page. Then it's safe to use LoadControl(type)

Thanks for reporting the issue.
Web Platform and Tools Team. Posted by Microsoft on 14/06/2005 at 6:31 PM

关于c# - 使用 LoadControl 方法动态加载 UserControl (Type, object[]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/450431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com