Completely remove ViewState for specific pages

二次信任 提交于 2019-11-28 00:44:13
Martin Smith

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);
}

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="" />

In the <% @page... directive at the top of the page, add EnableViewState="False". That will prevent the ViewState for that particular page.

The method suggested by Martin must be used very carefully; because it may cause unexpected behaviors in your pages as Martin pointed in parenthesis. I've actually experienced it. But there is another option to remove viewstate content from page safely.

This option gives you the ability to use viewstate without setting false, it also allows you to remove it from your pages. Please check the articles below:

1- http://www.eggheadcafe.com/articles/20040613.asp

2- http://aspalliance.com/72

There is a solution file zipped under the Peter's article [1] you can download. I recommend that you read the second article also referenced by Peter. This is a perfect solution to remove viewstate content from your page while using its capabilities.

Sean Moubry
Susantha

in .net4 you can just remove the runat="server" from the form tag. But you can't use server controls inside the form tag once you remove it.

ViewState is added only if an asp:Form is present in the page. Remove the Form, and the hidden field will not be rendered.

Beware: By doing this, you are also renouncing to have server-side event handlers, or any kind of PostBack events.

Or just use a simple jQuery line to remove the fields, if you're using AJAX-style postback requests...

$(".aspNetHidden").remove();

This removes the DIV encasing the hidden __VIEWSTATE fields.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!