In this article I will explain with an example, how to disable or remove ViewState Hidden Field in ASP.Net Page using C# and VB.Net.
Even after disabling the ViewState at Page level, Master Page level or in Web.Config, still the Hidden Field of the ViewState with some amount of encrypted data is rendered on Page as shown in the figure below.
There is no straight forward way to disable or remove the ViewState Hidden Field.
The only possible way to remove the ViewState Hidden Field is by removing it from the generated HTML of the Page with the help of Regular Expressions.
In order to achieve the above objective, the Render event will be overridden and the ViewState Hidden Field will be removed from the generated HTML.
You will need to import the following namespaces.
A new class named BasePage inheriting the Page class will be created. Inside this class, the Render event will be overridden and inside the Render event handler, the ViewState Hidden Field will be replaced with a Blank string using Regular Expressions, thus removing it from the generated HTML of the Page.
Note: The BasePage class will have to be inherited by all the Pages for which the ViewState Hidden Field needs to be removed.
public class BasePage : Page
protected override void Render(HtmlTextWriter writer)
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hWriter = new HtmlTextWriter(sw);
string html = sb.ToString();
html = Regex.Replace(html, "<input[^>]*id=\"(__VIEWSTATE)\"[^>]*>", string.Empty, RegexOptions.IgnoreCase);
Public Class BasePage
Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
Dim sb As StringBuilder = New StringBuilder
Dim sw As StringWriter = New StringWriter(sb)
Dim hWriter As HtmlTextWriter = New HtmlTextWriter(sw)
Dim html As String = sb.ToString
html = Regex.Replace(html, "<input[^>]*id=\""(__VIEWSTATE)\""[^>]*>", String.Empty, RegexOptions.IgnoreCase)
Inheriting the BasePage class
The BasePage class will now be inherited in the ASP.Net Page instead of the Page class.
public partial class _Default : BasePage
protected void Page_Load(object sender, EventArgs e)
Partial Class _Default
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
The ViewState Hidden Field has been removed from the Page