Earlgray
Earlgray

Reputation: 647

Where is ViewState store if it is disabled

I have property (in ASP.NET webforms) writen like this:

public string QuickSearchText
{
     get
     {
         string value = (string)ViewState["QuickSearchText"];
         return ((value == null) ? string.Empty : value);
     }
     set
     {
         ViewState["QuickSearchText"] = value;
     }
}

and if I turn off viestate in Web.config like this:

<pages enableViewState="false" />

my property still works.

So I need to know, where is this value which I put in ViewState["QuickSearchText"] stored?

Upvotes: 2

Views: 349

Answers (1)

Endri
Endri

Reputation: 804

I have tried to simulate your problem with the following example:

Web form has one label and one button as below

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        </div>
    </form>
</body>
</html>

Code behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    int cnt = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(ViewState["QuickSearchText"] != null)
        {
            Label1.Text = ViewState["QuickSearchText"].ToString();
        }
        else
        {
            Label1.Text = "No viewstate set";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        cnt++;
        ViewState["QuickSearchText"] = cnt.ToString();
    }
}

Solution is created from VS2017 with Web Form Template and the Web.config part that is modified is addition of enableViewState="false" as below

<pages enableViewState="false">
  <namespaces>
    <add namespace="System.Web.Optimization"/>
    <add namespace="Microsoft.AspNet.Identity"/>
  </namespaces>
  <controls>
    <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt"/>
  </controls>
</pages>

All the other configurations are untouched.

Every time I click the button I get No viewstate set so I can't reproduce your problem. If you remove enableViewState="false" from Web.config the second time you press the button, you get 1 as the text of the label.

So, if you set the value of enableViewState to false it doesn't get stored somewhere.

Upvotes: 2

Related Questions