【问题标题】:Is it possible to render a web control dynamically?是否可以动态呈现 Web 控件?
【发布时间】:2012-08-03 10:35:08
【问题描述】:

我们有一个 Web 控件,我们希望将其呈现到已加载页面上的 div 中。这需要在用户单击菜单中的超链接时发生。

Web 控件有一些在 C# 代码中动态添加到其中的 javascript 文件。

我们也没有使用 aspx 文件,而是想将 web 控件加载到普通的 html 页面上。

请让我知道最好的方法是什么,或者在我努力在网络上寻找有用的东西时将我引导到一篇文章。任何帮助表示赞赏。

【问题讨论】:

    标签: asp.net dynamic rendering web-controls


    【解决方案1】:

    您可以在字符串中动态呈现您的控件,将字符串发回并将其放置在您的 div 中。使用 ajax 调用后面的代码来呈现控件并返回结果。

        // load the control
        var oCConrol = Page.LoadControl("CustomControl.ascx");
    
        // here you need to run some initialization of your control
        //  because the page_load is not loading now.
    
        // a string writer to write on it
        using(TextWriter stringWriter = new StringWriter())
        {
          // a html writer
          using(HtmlTextWriter renderOnMe = new HtmlTextWriter(stringWriter))
          {
            // now render the control inside the htm writer
            oCConrol.RenderControl(renderOnMe);
    
            // here is your control rendered output.
            strBuild = stringWriter.ToString();
          }
        }
    

    另外,您只需制作一个额外的空 aspx 页面,其中仅包含您的控件并使用 Ajax 调用它,即可获得相同的结果。结果将再次成为控件

    javascript 怎么过都难,不能跟控件一起去。您不能将文本发回然后使其在控件内作为 javascript 运行,这必须分开进行。

    【讨论】:

    • 嗨,我们没有使用 aspx 文件,所以不能调用 Page.LoadControl,有什么方法可以在普通的 html 文件上执行此操作?
    • @xerxes 抱歉,但我不知道如何回答。
    【解决方案2】:

    我通过创建一个单独的、独立的 .aspx 页面和 Jquery ajax 做了类似的事情。使用 Jquery ajax 调用 .aspx 页面,并通过 ajax 响应从该页面返回所有呈现的 HTML。

    据我所知,没有任何方法可以在 .aspx 页面的上下文之外呈现 Web 控件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 2011-10-23
      • 2011-09-20
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      相关资源
      最近更新 更多