Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Completely remove ViewState for specific pages

I have a site that features some pages which do not require any post-back functionality. They simply display static HTML and don't even have any associated code. However, since the Master Page has a <form runat="server"> tag which wraps all ContentPlaceHolders, the resulting HTML always contains the ViewState field, i.e:

<input
  type="hidden"
  id="__VIEWSTATE"
  value="/wEPDwUKMjEwNDQyMTMxM2Rk0XhpfvawD3g+fsmZqmeRoPnb9kI="
/>

EDIT: I tried both variants of setting EnableViewState on page level with no luck at all:

<%@ Page Language="C#" EnableViewState="false" %>
<%@ Page Language="C#" EnableViewState="true" %>

I realize, that when decrypted, this value of the input field corresponds to the <form> tag which I cannot remove because it is on my master page. However, I would still like to remove the ViewState field for pages that only display static HTML. Is it possible?

like image 214
Kerido Avatar asked Mar 12 '10 13:03

Kerido


2 Answers

You could override Render and strip it out with a Regex.

Sample as requested. (NB: Overhead of doing this would almost certainly be greater than any possible benefit though!)

[edit: this function was also useful for stripping all hidden input boxes for using the HTML output as a word doc by changing the MIMEType and file extension]

protected override void Render(HtmlTextWriter output)
{
    StringWriter stringWriter = new StringWriter();

    HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter);
    base.Render(textWriter);

    textWriter.Close();

    string strOutput = stringWriter.GetStringBuilder().ToString();

    strOutput = Regex.Replace(strOutput, "<input[^>]*id=\"__VIEWSTATE\"[^>]*>", "", RegexOptions.Singleline);

    output.Write(strOutput);
}
like image 182
Martin Smith Avatar answered Sep 20 '22 14:09

Martin Smith


Add following methods to the page:

        protected override void SavePageStateToPersistenceMedium(object state)
    {
        //base.SavePageStateToPersistenceMedium(state);
    }

    protected override object LoadPageStateFromPersistenceMedium()
    {
        return null; //return base.LoadPageStateFromPersistenceMedium();
    }

    protected override object SaveViewState()
    {
        return null;// base.SaveViewState();
    }

Result :

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" />
like image 40
jimjim Avatar answered Sep 17 '22 14:09

jimjim