4

現在のページの HTML を取得する方法はありますか。現在のページとは、Default.aspx で作業していて、ボタンを提供して HTML を取得したいとします。

入手方法。

4

3 に答える 3

20

要件の明確化に応じて編集

ページの render メソッドをオーバーライドして、サーバー側で 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

Not sure why you want what you want, but... this is off the top of my head, i.e. I didn't try this code.

Add a client-side onclick to your button to show markup and do something like this:

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.
}

If you need this rendered markup posted back to the server for some reason, store the encoded markup in a hidden input and post that back. You can register the script below on the server-side using ClientScriptManager.RegisterOnSubmitStatement . Here's the cleint-side code.

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

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

Hope that helps, Nick

于 2009-03-18T04:45:46.710 に答える
-1

これであなたの目的が何であるかはまだわかりません。ただし、ページのレンダリングされた出力全体が必要な場合は、サーバーが完全にレンダリングされた HTML を返した後に実行されるため、クライアント側のコードを確認することをお勧めします。

それ以外の場合は、おそらくページのアンロード イベントをキャッチし、そこでレンダリングされたコンテンツで何かを行うことができます。

これから何を望むかについて、より多くの情報が必要です。

于 2009-02-10T09:37:03.267 に答える