以编程方式呈现Web UserControl

Con*_*ell 5 c# asp.net user-controls

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

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

但是,API怎么样?有没有什么办法可以简单地通过了解控件的类型来呈现此控件的HTML?该RenderControl方法没有任何HTML写的作家作为对照的生命周期还没有开始.

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

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

ric*_*ott 8

这是我最近所做的,效果很好,但是如果你在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)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)