简体   繁体   English

以编程方式呈现Web UserControl

[英]Programmatically rendering a web UserControl

I have a load of UserControl objects ( ascx files) in their own little project. 我在他们自己的小项目中有ascx UserControl对象( ascx文件)。 I then reference this project in two projects: The REST API (which is a class library project) and the main website. 然后我在两个项目中引用这个项目:REST API(这是一个类库项目)和主要网站。

I'm sure this would be easy in the website, simply use Controls.Add in any Panel or ASP.NET control would work. 我确信这在网站上很简单,只需在任何Panel或ASP.NET Controls.Add中使用Controls.Add即可。

However, what about the API? 但是,API怎么样? Is there any way I can render the HTML of this control, simply by knowing the type of the control? 有没有什么办法可以简单地通过了解控件的类型来呈现此控件的HTML? The RenderControl method doesn't write any HTML to the writer as the control's life cycle hasn't even started. RenderControl方法不会向writer写入任何HTML,因为控件的生命周期甚至还没有开始。

Please bare in mind that I don't have the controls in the web project, so I don't have a virtual path to the ascx file. 请记住,我没有Web项目中的控件,所以我没有ascx文件的虚拟路径。 So the LoadControl method won't work here. 所以LoadControl方法在这里不起作用。

All the controls actually derive from the same base control. 所有控件实际上都来自相同的基本控件。 Is there anything I can do from within this base class that will allow me to load the control from a completely new instance? 我可以在这个基类中做些什么来允许我从一个全新的实例加载控件?

This is what I have done recently, works well, but understand postbacks will not work if you use it inside your ASP.NET app. 这是我最近所做的,效果很好,但是如果你在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)
    {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM