簡體   English   中英

以編程方式呈現Web UserControl

[英]Programmatically rendering a web UserControl

我在他們自己的小項目中有ascx UserControl對象( ascx文件)。 然后我在兩個項目中引用這個項目:REST API(這是一個類庫項目)和主要網站。

我確信這在網站上很簡單,只需在任何Panel或ASP.NET Controls.Add中使用Controls.Add即可。

但是,API怎么樣? 有沒有什么辦法可以簡單地通過了解控件的類型來呈現此控件的HTML? RenderControl方法不會向writer寫入任何HTML,因為控件的生命周期甚至還沒有開始。

請記住,我沒有Web項目中的控件,所以我沒有ascx文件的虛擬路徑。 所以LoadControl方法在這里不起作用。

所有控件實際上都來自相同的基本控件。 我可以在這個基類中做些什么來允許我從一個全新的實例加載控件?

這是我最近所做的,效果很好,但是如果你在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)
    {
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM