Using the Items collection for state management
You can have a look at this post , this post , this post and this one.My last post was on Application state management and you can read it here.
In this post I will show you how to preserve state using the Items collection. Many developers do not know that we have this option as well for state management.
With Items state we can pass data between pages and I will show you how to do that with a hands-on example.
1) Launch Visual Studio 2005,2008/2010. Express editions will work fine. I am using Visual Studio 2010 Ultimate edition.
2) Create an empty asp.net web site. Choose an appropriate name. Choose C# as the development language.
3) Add an item to your website, a web form.Leave the default name.Drag and drop a 2 textboxes, a label and a button control on the form.We will want to pass the user's favourite team and colour to another web form. The markup for this web form could be something like this
<form id="form1" runat="server"> <div>enter your favourite team:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br />enter your favourite color:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </div> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" /> <p> </p> </form>4) Add a new item on your site, a web form and leave the default name (Default2.aspx). Add a label control on the form.
5) Add a new item to your website, a global application class, Global.asax.
6) In the Button1_Click event handling routine type,
string team = TextBox1.Text; string colour = TextBox2.Text;Context.Items["team"]=team;Context.Items[
"colour"]=colour;Server.Transfer(
"Default2.aspx");I use the Items collection to store the user's preferences.
7) In the Page_Load event handling routine of the Default2.aspx page type,
string myteam = (string)Context.Items["team"]; string mycolour = (string)Context.Items["colour"];Label1.Text =
"My team is " + myteam + " my color is " + mycolour;Run your application and insert your favourite team and colour in the textboxes. Hit the button and you will see your preferences being printed on the screen.
8) With Items state we can have data available to all our pages. We can do that by placing information when our application begins and then access the Items collection from an individual page.In the Global.asax page type,
void Application_BeginRequest(object sender, EventArgs e){
Context.Items["email"] = "info@mycompany.gr";
}
9) In the Page_Load event handling routine of the Default.aspx type,
string email = (string)Context.Items["email"];Label1.Text =
"My email is " + email;Run your application and you will see the email that was stored in the Items collection in the Application_BeginRequest being displayed on the screen.
Using Items state is not to most obvious choice or the most popular one. Most developers I know have never used it to implement state management. But as everything in ASP.Net development has its place.
Hope it helps!!!