using HTTPContext Object

In this article we will see what is HTTPContext object & how to make use of it.
The HttpContext object in the System.Web namespace encapsulates all of the information related to request & response of aspx page at an instance.
HttpContext object will be constructed newly for each & every request made by client, apart from Request & Response information it will contain Server, Session, Cache, User & etc.
Now let’s dig into code, & see how to find a control using HTTPContext Object

// HttpContext.Current.Request.Form gives all control names that are part of current
// request, this will give hidden field controls that are being used by asp.net engine

foreach (string ctrlName in HttpContext.Current.Request.Form)
{
// locate the control that you want to find
if (ctrlName.ToString() == “txtname”)
{
// will allow to get page object
Page page = HttpContext.Current.Handler as Page;

// now find control with page object & type cast
TextBox txt = (TextBox)page.FindControl(ctrlName);

// check if control object not null & assign the value
if(txt != null)
txt.Text = “Finally found the control”;
}
}

Ok this looks ok but you must be wondering why do I need to write this length of code to assign value.
Let’s look at the below scenario

HttpContext.Current:

The static property Current on the HttpContext class can be useful whenever the flow of control leaves the code in your Page.
Using this property you can reach out and magically grab the current Request, Response, Session, and Application objects (and more)
for the request you are servicing.

Take the following code as an example.

private void Page_Load(object sender, System.EventArgs e)
{
DemoClass dClass = new DemoClass();
dClass.DemoMethod();
}

DemoClass:

class DemoClass
{
public void DemoMethod()
{
HttpContext.Current.Response.Write(”Demo Method Class”);
}
}

This provides the ability to grab the context for the current request from any code inside the same
application domain is powerful.

Happy Kooding… Hope this helps!

Advertisements