When you create a web page without writing anything, you can run it. Then, you can View the Source code and see the following section.
At this moment, you may think that the webpage has an EnableViewState attribute, which can be set to False, but does not seem to have any effect.
In fact, ViewState on a webpage is not a bad thing, but sometimes we don't need it. What should I do?
First, let's look back at the first image, with 12th lines of code, that is, the highlighted part, which is the part we want to remove. We can use regular expressions and Render the webpage to remove them.
Reference namespace in. aspx. cs or. aspx. vb:
Copy codeThe Code is as follows: using System;
Using System. IO;
Using System. Text;
Using System. Text. RegularExpressions;
Using System. Web;
Using System. Web. UI;
Next, rewrite the Render () method.Copy codeThe Code is as follows: protected override void Render (HtmlTextWriter writer)
{
StringBuilder sb = new StringBuilder ();
StringWriter sw = new StringWriter (sb );
HtmlTextWriter hWriter = new HtmlTextWriter (sw );
Base. Render (hWriter );
String html = sb. ToString ();
Html = Regex. replace (html, "<input [^>] * id = \" (_ VIEWSTATE) \ "[^>] *>", string. empty, RegexOptions. ignoreCase );
Writer. Write (html );
}
Of course, the above is only for a single webpage. If you want to remove ViewState from multiple webpages, you can write it in a BasePage base class, implement the webpage, and inherit the BasePage.