Context Object in ASP.Net

Context object in ASP.Net

In previous post we learnt state management  Session and ViewState. In this post we will learn about Context object.

The Context object is same as 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 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;

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.

Context object in ASP.Net
Context Object in ASP.Net

C# code for above example

write below code on send button on first page.

Write below code on Page_Load events in nextpage.aspx page for retrieve context value.

(Visited 62 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha *