get HTML of current page without ViewState ASP.Net

前端 未结 3 1764
灰色年华
灰色年华 2020-12-18 09:03

Is there any way through which I can get HTML of my current page. By current page I mean let\'s say I am working on Default.aspx and want to get HTML by providing a button

相关标签:
3条回答
  • 2020-12-18 09:32

    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

    0 讨论(0)
  • 2020-12-18 09:33

    EDITED in response to clarification of the requirements

    You can override the page's render method to capture the HTML source on the server-side.

    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
    }
    
    0 讨论(0)
  • 2020-12-18 09:43

    I'm still not sure what your objective is with this. But if you want the total rendered output of the page then your probably better of looking at some client side code as this would be run once the server has returned the fully rendered HTML.

    Otherwise you could proably catch the page unload event and do something with the rendered content there.

    More info needed on what you want from this.

    0 讨论(0)
提交回复
热议问题