Software rendering web usercontrol

I have loading objects UserControl( ascxfiles) in their own small project. Then I refer to this project in two projects: the REST API (which is the class library project) and the main website.

I am sure it would be easy on the site, just use Controls.Addin any control Panelor ASP.NET.

However, what about the API? Is there a way to render the HTML of this control by simply knowing the type of control? The RenderControl method does not write any HTML file to the record because the control life cycle has not even begun.

Please note that I do not have controls in the web project, so I do not have a virtual file path ascx. Thus, LoadControl will not work here.

All controls are actually derived from the same basic control. Is there anything I can do from this base class that will allow me to load the control from a completely new instance?

+5
source share
2 answers

This is what I did recently, works well, but to understand that postbacks will not work if you use it in your ASP.NET application.

 [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)
    {
    }
}
+8
source
+1

All Articles