In this article I will go through a problem that myself was facing recently i.e. The ViewState Hidden Field.
Problem
Even if you disable the ViewState at page level, Master Page level and also in web.config, still you will see the hidden field contain some amount of encrypted data as shown in the figure below.
Solution
So directly there’s no way to get rid of the ViewState hidden field. But with a little trick we can do it. What we would do is we will modify the HTML that is rendered on the page and remove the ViewState hidden field from it. Thus when the page renders we will not see the ViewState hidden field
For this I create a Base Class that the ASP.Net Web Page will inherit on which you want to hide the ViewState hidden field.
C#
using System;
using System.Web;
using System.Text;
using System.Web.UI;
using System.IO;
using System.Text.RegularExpressions;
public class BasePage : Page
{
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);
}
}
VB.Net
Imports System
Imports System.Web
Imports System.Text
Imports System.Web.UI
Imports System.IO
Imports System.Text.RegularExpressions
Public Class BasePage
Inherits Page
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)
MyBase.Render(hWriter)
Dim html As String = sb.ToString
html = Regex.Replace(html, "<input[^>]*id=\""(__VIEWSTATE)\""[^>]*>", String.Empty, RegexOptions.IgnoreCase)
writer.Write(html)
End Sub
End Class
As you will notice above I am overriding the Render event of the ASP.Net Web page and then replacing the ViewState hidden field with a blank string using the Regular Expressions.
Now you just need to inherit the BasePage class that we generated instead of the default ASP.Net Page class as shown below.
C#
public partial class _Default : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
VB.Net
Partial Class VB
Inherits BasePage
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
The figure below displays the screenshot of the page without any ViewState hidden field.
Downloads
You can download the complete source code in C# and VB.Net using the download link provided below.
RemoveViewstateHiddenField.zip