Farewell to ViewState - 2, or to the base of it!

    Another round of tough confrontation with ViewState. This time we will try to save it in the SQL Server database.
    We repeat the theory a little. We have a PageAdapter class , the use of which can “adapt” an aspx page to a specific browser (in our case, to everyone). Using this adapter, you can override the functionality for loading and saving ViewState (using the GetStatePersister method ).

    So, the procedure:

    - create a simple structure in the database for storing ViewState: We also create stored procedures for receiving, saving and cleaning (obsolete) ViewState; - inherit the PageStatePersister class



    , in it we redefine the Load and Save methods to implement loading and saving the ViewState, respectively:
    namespace SqlStatePersister
    {
      public class SqlPageStatePersister : PageStatePersister
      {
        private Page _page;

        public SqlPageStatePersister(Page page)
          : base(page)
        {
          _page = page;
        }

        public override void Load()
        {
          // функционал загрузки и десериализации ViewState
        }

        public override void Save()
        {
          // функционал сериализации и сохранения ViewState
        }

      }
    }

    * This source code was highlighted with Source Code Highlighter.

    - we inherit the PageAdapter class, in it we redefine the GetStatePersister method so that it returns an instance of the class defined in the first step:
    namespace SqlStatePersister
    {
      public class SqlPageAdapter : PageAdapter
      {
        public override PageStatePersister GetStatePersister()
        {
          return new SqlPageStatePersister(Page);
        }
      }
    }

    * This source code was highlighted with Source Code Highlighter.


    - using the .browser file we “adapt” the page:

      
        
          
        

      



    * This source code was highlighted with Source Code Highlighter.


    - optionally add buns, for example, the gzip-compression functionality before saving to the database;

    - create a sheduler (for example, SQL Server Job), which will clean the table from obsolete ViewState;

    - PROFIT!

    The example (VS 2010 solution, .NET 4) uses the AdventureWorks database , which replaced Northwind as an example. For the application to work, you must have the ViewStateCompress setting in the appSettings, which is set to 1 if gzip compression is needed, or 0 if not needed. In the connectionStrings section, you also need a database connection string in which the ViewState will be stored (in my example this is a separate database, created by executing the install.sql script from the solution).

    Thanks for attention! If more detailed comments on the project are required, I am at your service;)

    PS Based on the Store ViewState in the Database instead of Hidden Form Field and ViewState Compression .

    Also popular now: