State Management techniques in asp.net has two types i.e. Client Side and Server Side. Let us discuss client side state management.
There are 5 ways to manage client side state management.
- It is used to store small amount of data and works just like any other web control.
- Stores only value at one point of time.
- As per the name it is not visible to the user.
- It will travel with every request made by the user.
<asp:HiddenField ID=”HiddenField1″ runat=”server” />
- A client side state management technique.
- There will be sometimes a requirement where you need to maintain the state after the page is posted back to the server.
- Internally to store data it uses hidden field.
- It is a page level management technique i.e. the state is preserved until the page is accessed by the user.
- It is enabled by default.
Viewstate[“variablename”] = value;
- Cookie is a text file created when the user visits a specific website and if the website wants to store data which might be required to identify the user if he is visiting file.
- It is stored in users hard drive and created by the browser.
- If the user comes back to the same website which he had visited previously then the website will check whether the user has visited prior with the help of the cookie and if the information is present then the user will be logged in.
- For this the same cookie information is used for or it will be treated as new request.
- Cookie has further 2 types : Persistent Cookie and Non Persistent Cookie
- Persistent Cookie : This type of are of permanent type up-till the time you set. More over you can set the expiry date time.
- Non Persistent Cookie : This type of cookie are of temporary type and works until the same browser is open.
- When user browser closes the cookie is discarded.
- They are useful for public computers.
Syntax : Persistence Cookie
HttpCookie cookieobject = new HttpCookie(“Persistance”);
cookieobject.Expires = DateTime.Now.AddSeconds(10);
Syntax : Non Persistent Cookie
HttpCookie noncookieobj = new HttpCookie(“NonPersistance”);
noncookieobj.Value = “This is A Non Persistance Cookie;
Limitation of Cookies
- No. of cookies varies and is limited as per each browser.
- Generally 20 cookies per server are allowed by the browser.
- Size cannot exceed more than 4096 bytes i.e. 4kb including name and data.
- It is used for custom controls created by the user.
- It has to be used if the user has explicitly disabled view state.
- You need to override OnInit() method of the control and add a Page.RegisterRequiresControlState() method using the object of the control to register.
- After this step now we need to over ride LoadControlState and SaveControlState to save the data for maintaining states.