Programmatically rendering a web UserControl

后端 未结 1 381
醉酒成梦
醉酒成梦 2020-12-30 15:44

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 i

相关标签:
1条回答
  • 2020-12-30 16:14

    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)
        {
        }
    }
    
    0 讨论(0)
提交回复
热议问题