编程方式渲染一个Web用户控件 [英] Programatically rendering a web UserControl

查看:99
本文介绍了编程方式渲染一个Web用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在自己的小项目用户控件对象( ASCX 文件)的负荷。然后,我引用两个项目这个项目。的REST API(这是一个类库项目)和主网站

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.

我敢肯定,这将是很容易在网站上,只需使用 Controls.Add被中的任何面板或ASP.NET控件会工作。

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

不过,有关API的是什么?有什么办法,只要知道控件的类型,我可以呈现此控件的HTML?该 RenderControl 方法不能写任何HTML,以笔者作为控制的生命周期还没有开始。

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.

裸请记住,我没有在web项目中的控制,所以我没有在 ASCX 文件的虚拟路径。因此, LoadControl 方法不会在这里工作。

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?

推荐答案

这是我最近做,效果很好,但如果你使用它的ASP.NET应用程序内了解回传将无法工作。

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

这篇关于编程方式渲染一个Web用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆