Context object in ASP.Net
In previous asp.net post we learnt state management Session and ViewState. In this post we will learn about Context object.
The asp.net Context object is same as asp.net session object. But the Context will be null when page posted to server while Session can store values on post back.
We must use Server.Transfer method for redirection when we use Context in asp.net. If we use Response.Redirect method for redirect to other page the page complete the round trip of post back so Context will be null.
The main difference between Context object and Session:
- With Context object we must use Server.Transfer method for redirect to other page.
- If we use Response.Redirect method with Context then the Context value will be null on other page.
- With Session we use both method for redirect.
Syntax of Context
Declare and assign value to Context object.
Context.Items[“Id”] = value;
Server.Transfer(“NextPage.aspx”);
Retrieve Context value on NextPage.aspx
string myvalue = Context.Items[“Id”].ToString();
Response.Write(“Your Value = “+ myvalue);
Context Object Example in ASP.Net
Open visual studio and design web form with textbox control along with a button control. Here, we will send textbox value to other page nextpage.aspx using context object and we use Server.Transfer method for redirect to other page. In nextpage.aspx page on Page_Load events we will retrieve value from context and display it in label control.
C# code for above example
write below code on send button on first page.
protected void btnsessiontimeout_Click(object sender, EventArgs e)
{
Context.Items["name"] = txtname.Text;
Server.Transfer("NextPage.aspx");
}
Write below code on Page_Load events in nextpage.aspx page for retrieve context value.
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Welcome = " + Context.Items["name"].ToString();
}
Related ASP.Net Topics :
Session State in C#.Net
Application State in C#.Net
Subscribe us
If you liked this asp.net post, then please subscribe to our YouTube Channel for more asp.net video tutorials.
We hope that this asp.net c# tutorial helped you to understand about Context Object in C#.
Next asp.net tutorial we will understand difference between Response.Redirect() and Server.Transfer() in C#.