Sunday 8 January 2012

Compare Session state and Viewstate in .NET?

What is viewstate in ASP.NET?

The viewstate question should be well prepared before any ASP NET Interview.


Viewstate object is used to persist data of variables across postbacks. It even existed inclassic ASP. In ASP.NET, a variable's value is assigned to a a viewstate object and then this is passed as a hidden variable and then may be retrieved by a page after a postback. See the example below...



//Save the value in ViewState object before the PostBack

ViewState("SomeVar") = txtFirstName.text;

//Retrieve the value from ViewState object after the PostBack

String strFirstName = ViewState("SomeVar").ToString();

Note that Viewstate object's value is accessible only at page level. This means that if a viewstate is created at page1.aspx, then it may be used only within page1.aspx after the postback, and cannot be used by any other page. To know how to pass values from one page to another



What is Session in ASP.NET?

Session state is the feature of ASP.NET based web applications using which values of a variable may be persisted and then posted to another page

Following C# Syntax Is Used To Add Session

Session..Add(key,value);

Example:
Session.Add("Name",TextBox1.Text);

To Retrieve The Session Value Use The Following Syntax

returnValue = Session[key];

Example:
string userName = Session["Name"].ToString();


No comments:

Post a Comment