View State
View State is a Client Side management technique which is used to hold values even after the postback. It is mainly used for storing temporary data like small calculations, final results etc. It is a page level state management which means it holds value only for the current page where you have added the view state code. We cannot used this technique to store values across webpages.
View State values are stored in the generated HTML hidden field. View State is enabled by default is every ASP.NET page.
Lets take the same example which we have used in "Chapter 7: Why HTTP protocol is called stateless protocol?"
Design
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace httpstateless
{
public partial class ViewState : System.Web.UI.Page {
string name, blog;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
name = TextBox1.Text;
blog = TextBox2.Text;
TextBox1.Text = "";
TextBox2.Text = "";
ViewState["name"] = name;
ViewState["blog"] = blog;
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Text = Convert.ToString(ViewState["name"]);
TextBox2.Text = Convert.ToString(ViewState["blog"]);
}
}
}
Output
Before clicking save:
After Restore:
If you right click the page and then select view page source you can find an input field which has type="hidden". This is automatically created. All viewstate values are stored here in encrypted format.
Points to remember
You may click the Content tab to see all the posts that i will cover in this tutorial for easy navigation.
Design
Code Behind
using System;
using System.Collections.Generic;using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace httpstateless
{
public partial class ViewState : System.Web.UI.Page {
string name, blog;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
name = TextBox1.Text;
blog = TextBox2.Text;
TextBox1.Text = "";
TextBox2.Text = "";
ViewState["name"] = name;
ViewState["blog"] = blog;
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Text = Convert.ToString(ViewState["name"]);
TextBox2.Text = Convert.ToString(ViewState["blog"]);
}
}
}
Output
Before clicking save:
After Clicking save:
If you right click the page and then select view page source you can find an input field which has type="hidden". This is automatically created. All viewstate values are stored here in encrypted format.
Points to remember
- View State is a page level state management technique.
- It can hold any type of data.
- It is stored in the hidden field.
- It is mainly used to store temporary data.
- It is not used to store large data.
You may click the Content tab to see all the posts that i will cover in this tutorial for easy navigation.
No comments:
Post a Comment