Programmatically rendering a web UserControl

試著忘記壹切 提交于 2019-12-30 02:33:06

问题


I have a load of UserControl objects (ascx files) in their own little project. I then reference this project in two projects: The REST API (which is a class library project) and the main website.

I'm sure this would be easy in the website, simply use Controls.Add in any Panel or ASP.NET control would work.

However, what about the API? Is there any way I can render the HTML of this control, simply by knowing the type of the control? The RenderControl method doesn't write any HTML to the writer as the control's life cycle hasn't even started.

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. So the LoadControl method won't work here.

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?


回答1:


This is what I have done recently, works well, but understand postbacks will not work if you use it inside your ASP.NET app.

 [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)
    {
    }
}


来源:https://stackoverflow.com/questions/8088427/programmatically-rendering-a-web-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!