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

标签 c# asp.net

我正在尝试通过页面方法返回用户/服务器控件的 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/

相关文章:

c# - CloudBlockBlob AcquireLease 为两个辅助角色提供两个租约

c# - 为什么 FileStream 不可写?

c# - 如何在 asp.net 的代码隐藏中获取 html 按钮中的隐藏字段值

c# - 如何从 asp.net-membership 获取用户名和 userID 并将其绑定(bind)到下拉列表?

php - 从实现 AJAX 分页的所有 asp.net 页面中抓取数据

c# - 如何在不指定通用参数的情况下将实现实例转换为接口(interface)(实现知道)?

c# - 如何在 .NET Interop.Excel.Workbooks.OpenText 中指定编码

c# - 使用/clr 编译现有的 C++ 代码,然后从 C# 调用它

c# - 如何将错误和其他消息从 DAL/业务层向上传递到 UI 层?

c# - 使用参数调用resx