【问题标题】:get HTML of current page without ViewState ASP.Net在没有 ViewState ASP.Net 的情况下获取当前页面的 HTML
【发布时间】:2009-02-10 09:25:53
【问题描述】:

有什么方法可以让我获得当前页面的 HTML。当前页面是指假设我正在处理 Default.aspx 并希望通过在其上提供一个按钮来获取 HTML。

如何获得。

【问题讨论】:

  • “获取 HTML”是什么意思?您需要在服务器端访问它,还是想向您的用户展示它?您将如何使用这些信息,以及用于什么目的?
  • get HTMl——我的意思是我想通过点击一个按钮来获取页面的渲染 HTML
  • 我还是不明白...你想有“源代码”在哪里?单击按钮时会发生什么?您是要处理服务器端的代码还是直接将其添加到用户的剪贴板?你在这方面的成就是什么,所以我们都可以理解
  • 我想要的只是得到渲染的 HTML .. 这会像-- HelloSome Content
  • 您希望能够在客户端还是服务器端使用它,您希望它如何呈现?

标签: asp.net html rendering


【解决方案1】:

针对要求的澄清进行了编辑

您可以覆盖页面的渲染方法以在服务器端捕获 HTML 源代码。

protected override void Render(HtmlTextWriter writer)
{
    // setup a TextWriter to capture the markup
    TextWriter tw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(tw);

    // render the markup into our surrogate TextWriter
    base.Render(htw);

    // get the captured markup as a string
    string pageSource = tw.ToString();

    // render the markup into the output stream verbatim
    writer.Write(pageSource);

    // remove the viewstate field from the captured markup
    string viewStateRemoved = Regex.Replace(pageSource,
        "<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\".*?\" />",
        "", RegexOptions.IgnoreCase);

    // the page source, without the viewstate field, is in viewStateRemoved
    // do what you like with it
}

【讨论】:

  • 也许他/她不喜欢你:)
  • 为什么页面加载时这个方法没有被调用?
【解决方案2】:

不知道你为什么想要你想要的,但是......这不是我的想法,即我没有尝试这个代码。

为您的按钮添加一个客户端 onclick 以显示标记并执行以下操作:

function showMarkup() {
      var markup = "<html>" + document.getElementsByTagName("html")[0].innerHTML + "</html>";

      alert(markup); // You might want to show a div or some other element instead with the markup variable as the inner text because the alert might get cut off.
}

如果您出于某种原因需要将此呈现的标记发回服务器,请将编码的标记存储在隐藏的输入中并将其发回。您可以使用 ClientScriptManager.RegisterOnSubmitStatement 在服务器端注册以下脚本。这是客户端代码。

var markup = escape("<html>" + document.getElementsByTagName("html")[0].innerHTML + "</html>");
var hiddenInput = $get('hiddenInputClientId');

if (hiddenInput) {
      hiddenInput.value = markup;
}

希望对您有所帮助, 尼克

【讨论】:

    【解决方案3】:

    我仍然不确定您的目标是什么。但是,如果您想要页面的总渲染输出,那么您可能最好查看一些客户端代码,因为一旦服务器返回完全渲染的 HTML,这将运行。

    否则,您可能会捕获页面卸载事件并在那里处理呈现的内容。

    需要更多信息来了解您想要从中得到什么。

    【讨论】:

    • 不知道为什么这被否决了,澄清后我会同意卢克(赞成他的回答)
    • 一个可能的案例(三年后):希望根据用户在网站上的输入/操作将 .Net 动态页面呈现为 PDF。
    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 2014-12-18
    • 2014-09-20
    • 1970-01-01
    • 2013-04-24
    • 2023-03-25
    相关资源
    最近更新 更多