Search
Submit & Win
Submit and win
Cash Prizes !
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Articles Author
Fri, 19-Dec-2014 Authors
All Time Authors
Sourav.Kayal
39750
SheoNarayan
38550
Niladri.biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads
 Article

ViewState Patterns in ASP.NET

Sudhakarj21
Posted by under Design Pattern & Practices category on for Intermediate level | Views : 9171 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Viewstate is one of the commonly use store to maintain state in page. For page level data or control data. But we need to think of some scenarios before using view state. This pattern helps to better manage ViewState in asp.net.

Purpose

ViewState is having it’s own advantages and disadvantage. To over come all the disadvantage we need to hack the view state to take its advantage and to hide its disadvantage.

To Whom

Most of the .NET controls uses view state to maintain state. And the view state will be very huge if are using Grid View, Data Grid or other rich asp.net controls. This document helps developers and designers to go though the under laying layer of view state management.

Overview

ViewState helps us a lot to store state of a control or a component in page level. ViewState is a form of store where it is capable of storing any serializable objects. This ViewState play a key role in handling post back events. For example if you have TextBox control on the page and user modified the text and you want to handle the text changed event. How ASP.NET knows that the text box value is changed ? It maintains state of the object so comparing old value with new value ASP.NET know to raise the text changed event. 

ViewState is maintained in Page Life Cycle. It is part page events. Below picture shows the page life cycle.


By default asp.net serializes and desterilizes the ViewState data using LosFormatter / ObjectStateFormatter (.NET 1/.NET 2). Formatters serializes data which is HTML compatible. Below example show how this works.

C# Code:

protected void Page_Load(object sender, System.EventArgs e)

    {

        ViewState["myOwnData"] = 10.0M;

    }

View State Decoder:

You can download the tool from http://www.pluralsight.com/community/media/p/51688.aspx



You can see the ViewState string and the decoded tree graph. This uses the LosFormatter / ObjectStateFormatter to deserialize the data. 

ASP.NET 1.x uses LosFormatter

ASP.NET 2.0 uses ObjectStateFormatter which helps to reduce the output size. For more details check http://nikhilk.net/ViewStateImprovements.aspx

Advantage:

1.   No need of server memory for saving the state of the page level data

2.   Easy to use and maintain data in ViewState<!--[endif]-->

3.   ReLoading and binding of data will be taken care inside the controls like GridView etc…

4.   Servers as page store with all the features required.

Disadvantages

1.   Process overhead for server to Seialize and Deserialize

2.   Secuirty issues if sensitive data is stored in view state. Can use MAC encryption but also increases server processing time.

3.   Increases the page size because the view state is stored in Base64 string

To avoid all the disadvantage most of the designers and developers prefer to turn off ViewState. This leads to manual reloading and rebinding of data for the controls which needs a data store like GridView, DataGrid etc…

It is better to use ViewState in scenarios where network bandwidth is good and page size doesn’t exceed more than 30KB. If there is enough network bandwidth and high server processing capacity we can use default asp.net ViewState capabilities. But below are some of the considerations which we can follow to over come some of the disadvantages of ViewState. Before going to these we need to know the events where we can maintain ViewState. ASP.NET page is having two methods to handle ViewState. 

  1. SavePageStateToPersistenceMedium: This method will serialize the ViewState and writes to the Page output.
  2. LoadPageStateFromPersistenceMedium: This method will deserialize the data and loads to the ViewState
Patterns & Practices

 

  1. Split the ViewState into small chunks instead of large single object.
    1. This will help the new browsers like IE6 and later and Mozilla for faster data transfer
    2. If you are using ASP.NET 2.0 or later you can set the below property for the page MaxPageStateFieldLength.
    3. But for ASP.NET 1.x below is the logic

C# Code:

protected override void SavePageStateToPersistenceMedium(object viewState)

    {

        LosFormatter format = new LosFormatter();

        StringWriter writer = new StringWriter();

        format.Serialize(writer, viewState);

        StringBuilder s = new StringBuilder(writer.ToString());

 

        int cnt = 1;

        int left = s.Length;

 

        while( left > 0 )

        {

            //Change to any value other than 1000 as necessary

            int cut = (left > 1000) ? 1000 : left;

 

            RegisterHiddenField("__VIEWSTATE" + cnt.ToString(),

            s.ToString().Substring(0,cut));

 

            s = s.Remove(0,cut);

            left -= cut;

            cnt++;

        }

        cnt--;

 

        RegisterHiddenField("__VIEWSTATE0", cnt.ToString());

        RegisterHiddenField("__VIEWSTATE", "");

    }

 

    protected override object LoadPageStateFromPersistenceMedium()

    {

        LosFormatter format = new LosFormatter();

        int cnt = Convert.ToInt32(Request["__VIEWSTATE0"].ToString());

        StringBuilder s = new StringBuilder();

 

        for (int i = 1; i <= cnt; i++)

        {

            s.Append(Request["__VIEWSTATE" + i.ToString()].ToString());

        }

        return format.Deserialize(s.ToString());

    }

  

  1. Compress the ViewState also helps to reduce the data transfer from server to client. But it will also increase the process usage on server. You can use ObjectStateFormatter in place of LosFormatter in the below code.

C# Code:

 

protected override void SavePageStateToPersistenceMedium(object state)

        {

            LosFormatter mFormater = new LosFormatter();

            MemoryStream ms = new MemoryStream();

            GZipStream gs = new GZipStream(ms, CompressionMode.Compress);

            mFormater.Serialize(gs, state);

            gs.Flush();

            gs.Close();

            byte[] output = ms.ToArray();

            string myOut = System.Convert.ToBase64String(output);

            ClientScript.RegisterHiddenField("__VSTATE", myOut);

        }

 

        protected override object LoadPageStateFromPersistenceMedium()

        {

            if (Request.Form["__VSTATE"] != null)

            {

                string vState = this.Request.Form["__VSTATE"];

                byte[] bytes = System.Convert.FromBase64String(vState);

                if (bytes.Length > 0)

                {

                    MemoryStream ms = new MemoryStream();

                    GZipStream gs = new GZipStream(ms, CompressionMode.Decompress);

                    ms.Write(bytes, 0, bytes.Length);

                    LosFormatter format = new LosFormatter();

                    object outputObj = format.Deserialize(gs);

                    gs.Close();

                    ms.Close();

                    return outputObj;

                }

            }

            return base.LoadPageStateFromPersistenceMedium();

        }

 
  1. Alternate storing of ViewState on server. In session object or in any other medium will reduce the Page size. If we use session object then we need more memory on the server and if there is no limitation on the hardware then we can use this.

C# Code:

private string _pageGuid = null;

    public string PageGuid

    {

        get

        {

            //Do we have it already? Check the Form, this could be a post back

            if (_pageGuid == null)

                _pageGuid = this.Request.Form["__VIEWSTATE_KEY"];

            //No? We'll need one soon.

            if (_pageGuid == null)

                _pageGuid = Guid.NewGuid().ToString();

            return _pageGuid;

        }

        set

        {

            _pageGuid = value;

        }

    }

     protected override object LoadPageStateFromPersistenceMedium()

    {

        return Session[this.PageGuid];

    }

 

    protected override void SavePageStateToPersistenceMedium(object viewState)

    {

        RegisterHiddenField("__VIEWSTATE_KEY", this.PageGuid);

        Session[this.PageGuid] = viewState;

    }

 
  1. Enable MAC key to encrypt ViewState to avoid security issues
  2. Disable ViewState in scenarios where it is not used. Will remove the over head on server.


Please provide your feedback to come up with such more articles.

Thanks,
Sudhakar

Always check your page size on the client side and make sure it is less than 30KB. Which is an industry standard followed by most of the companie

Page copy protected against web site content infringement by Copyscape
About the Author

Sudhakarj21

Full Name: Sudhakar Kottapalli
Member Level: Bronze
Member Status: Member
Member Since: 10/5/2009 7:05:50 AM
Country:

Login to vote for this post.
Share this to:

Bookmark It

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)