4

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

如何得到它。

4

3 回答 3

20

为响应要求的澄清而编辑

您可以覆盖页面的渲染方法以在服务器端捕获 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
}
于 2009-02-10T10:24:41.250 回答
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;
}

希望有帮助,尼克

于 2009-03-18T04:45:46.710 回答
-1

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

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

需要更多关于你想要什么的信息。

于 2009-02-10T09:37:03.267 回答