【问题标题】:Programmatically rendering a web UserControl以编程方式呈现 Web UserControl
【发布时间】:2011-11-11 00:51:31
【问题描述】:

我在他们自己的小项目中有大量UserControl 对象(ascx 文件)。然后我在两个项目中引用这个项目:REST API(这是一个类库项目)和主网站。

我相信这在网站上会很容易,只需在任何 Panel 中使用 Controls.Add 或 ASP.NET 控件即可。

但是,API 呢?有什么方法可以呈现这个控件的 HTML,只需知道控件的类型? RenderControl 方法不会向编写器写入任何 HTML,因为控件的生命周期甚至还没有开始。

请记住,我在 Web 项目中没有控件,因此我没有指向 ascx 文件的虚拟路径。所以LoadControl 方法在这里不起作用。

所有控件实际上都派生自同一个基本控件。我可以在这个基类中做些什么来让我从一个全新的实例中加载控件?

【问题讨论】:

    标签: c# asp.net user-controls


    【解决方案1】:

    这是我最近所做的,效果很好,但是如果您在 ASP.NET 应用程序中使用它,回发将不起作用。

     [WebMethod]
     public static string GetMyUserControlHtml()
     {
         return  RenderUserControl("Com.YourNameSpace.UI", "YourControlName");
     }
    
     public static string RenderUserControl(string assembly,
                 string controlName)
     {
            FormlessPage pageHolder = 
                    new FormlessPage() { AppRelativeTemplateSourceDirectory = HttpRuntime.AppDomainAppVirtualPath }; //allow for "~/" paths to resolve
    
            dynamic control = null;
    
            //assembly = "Com.YourNameSpace.UI"; //example
            //controlName = "YourCustomControl"
            string fullyQaulifiedAssemblyPath = string.Format("{0}.{1},{0}", assembly, controlName);
    
            Type type = Type.GetType(fullyQaulifiedAssemblyPath);
            if (type != null)
            {
                control = pageHolder.LoadControl(type, null);
                control.Bla1 = "test"; //bypass compile time checks on property setters if needed
                control.Blas2 = true;
    
            }                          
    
            pageHolder.Controls.Add(control);
            StringWriter output = new StringWriter();
            HttpContext.Current.Server.Execute(pageHolder, output, false);
            return output.ToString();
     }
    
    
    public class FormlessPage : Page
    {
        public override void VerifyRenderingInServerForm(Control control)
        {
        }
    }
    

    【讨论】:

    • 看起来不错的瑞克。现在只是想在我的结构中实现它。我注意到一件事 - HtmlForm form = new HtmlForm();。这个变量从不使用,因为form.Controls.Add被注释掉了?我错过了什么吗?
    • 我会更新,有一种方法可以处理常规表单,但是如果您的控件没有表单标签或者您没有以编程方式添加标签,您将收到运行时错误。这就是 FormLessPage 类为您绕过的内容。
    猜你喜欢
    • 2021-09-07
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多