首页 文章

使用Build Manager类加载ASPX文件并填充其控件

提问于
浏览
6

我使用BuildManager类来加载动态生成的ASPX文件,请注意它没有相应的.cs文件 .

使用以下代码我能够加载aspx文件,我甚至可以遍历动态创建的aspx文件的控件集合,但是当我为控件分配值时,它们没有显示出来 . 例如,如果我将值“Dummy”绑定到aspx页面的TextBox控件,则文本框保持为空 .

这是我正在使用的代码

protected void Page_Load(object sender, EventArgs e)
    {
        LoadPage("~/Demo.aspx");
    }
    public static void LoadPage(string pagePath)
    {
        // get the compiled type of referenced path
        Type type = BuildManager.GetCompiledType(pagePath);


        // if type is null, could not determine page type
        if (type == null)
            throw new ApplicationException("Page " + pagePath + " not found");

        // cast page object (could also cast an interface instance as well)
        // in this example, ASP220Page is a custom base page
        System.Web.UI.Page pageView = (System.Web.UI.Page)Activator.CreateInstance(type);

        // call page title
        pageView.Title = "Dynamically loaded page...";

        // call custom property of ASP220Page
        //pageView.InternalControls.Add(
        //    new LiteralControl(" Served dynamically..."));

        // process the request with updated object
        ((IHttpHandler)pageView).ProcessRequest(HttpContext.Current);
        LoadDataInDynamicPage(pageView);

    }
    private static void LoadDataInDynamicPage(Page prvPage)
    {
        foreach (Control ctrl in prvPage.Controls)
        {
            //Find Form Control
            if (ctrl.ID != null)
            {
                if (ctrl.ID.Equals("form1"))
                {
                    AllFormsClass cls = new AllFormsClass();
                    DataSet ds = cls.GetConditionalData("1");
                    foreach (Control ctr in ctrl.Controls)
                    {
                        if (ctr is TextBox)
                        {
                            if (ctr.ID.Contains("_M"))
                            {

                                TextBox drpControl = (TextBox)ctr;
                                drpControl.Text = ds.Tables[0].Rows[0][ctr.ID].ToString();
                            }
                            else if (ctr.ID.Contains("_O"))
                            {

                                TextBox drpControl = (TextBox)ctr;
                                drpControl.Text = ds.Tables[1].Rows[0][ctr.ID].ToString();
                            }
                        }
                    }
                }
            }
        }


    }

1 回答

  • 4

    我看到你从How To Dynamically Load A Page For Processing获得了部分代码 . 请阅读Mike的评论one .

    反转这个:

    ((IHttpHandler)pageView).ProcessRequest(HttpContext.Current);
    LoadDataInDynamicPage(pageView);
    

    对此:

    LoadDataInDynamicPage(pageView);
    ((IHttpHandler)pageView).ProcessRequest(HttpContext.Current);
    

    在这种情况下,更改调用的顺序确实会改变我认为的最终结果 . Commutativity property的倒数 . :)

相关问题