35

I am trying to improve performance of my web portal. I'm using Session to store state information.

But I heard that using session will decrease the speed of the application. Is there any other way to pass values across the page in asp.net.

Cees Meijer
  • 742
  • 2
  • 8
  • 23
Optimus
  • 2,200
  • 8
  • 37
  • 71
  • It's not bad to use `session` but there are may factors in using session. No of user. Your bandwidth. Sever capacity. If you have good of the above mentioned you can use `session`. – शेखर Feb 19 '13 at 11:19
  • @ssilas777 normally `cache` is same for all the users. So in his case he can't use cache. – शेखर Feb 19 '13 at 11:20
  • It depends on cache location at client side or server – ssilas777 Feb 19 '13 at 11:24
  • 2
    Checkout this MSDN post on State Management - it offers a great insight into ALL the options (both client and servside) and the Pro's and Con's of each http://msdn.microsoft.com/en-us/library/75x4ha6s(v=vs.100).aspx – Luke Baughan Feb 19 '13 at 11:36
  • What about using localStorage? – Deadeye Aug 29 '21 at 14:42

5 Answers5

65

You can pass values from one page to another by followings..

Response.Redirect
Cookies
Application Variables
HttpContext

Response.Redirect

SET :

Response.Redirect("Defaultaspx?Name=Pandian");

GET :

string Name = Request.QueryString["Name"];

Cookies

SET :

HttpCookie cookName = new HttpCookie("Name");
cookName.Value = "Pandian"; 

GET :

string name = Request.Cookies["Name"].Value;

Application Variables

SET :

Application["Name"] = "pandian";

GET :

string Name = Application["Name"].ToString();

Refer the full content here : Pass values from one to another

FLICKER
  • 6,439
  • 4
  • 45
  • 75
Pandian
  • 8,848
  • 2
  • 23
  • 33
  • 8
    `-1` for the cookies, and the Application. Especial the Application is not working if you use webgarden or webfarm !. And the application variables are a simple Dictionary<> that exist only for compatibility with the old asp and is not to be used. Also the cookies are not for transfer data from page to page like that. Very bad design, not good practice. – Aristos Feb 19 '13 at 13:03
  • @Aristos, does the -1 apply when the data is (to be) stored as a cookie? If each page must retrieve the data from a cookie and store modified values to a cookie then is there any value in storing the data elsewhere **also**? – Sam Hobbs Mar 29 '16 at 23:44
  • @user34660 In general in cookie we store very small amount of data, usually some id, then we connect that id with the real data with a database, or some other place. - Also is not good to pass values from page to page with cookie, is lead to bugs – Aristos Mar 30 '16 at 08:39
  • @Aristos, what if there is no large amount of data, just a small amount of data? What if the data is being stored as a cookie? Are you saying we should never use cookies for anything? If something is being stored as a cookie and it is also used in multiple pages then we are not passing values from page to page, right? I get the impression you will always insist that it is a bad idea so it is a bad idea for me to keep trying to explain what I am trying to say. I will let others decide, but a -1 implies it should **never** be done. – Sam Hobbs Apr 03 '16 at 05:20
  • Where is the HttpContext method? – Mandeep Jain Dec 21 '16 at 07:12
32

There are multiple ways to achieve this. I can explain you in brief about the 4 types which we use in our daily programming life cycle.

Please go through the below points.

1 Query String.

FirstForm.aspx.cs

Response.Redirect("SecondForm.aspx?Parameter=" + TextBox1.Text);

SecondForm.aspx.cs

TextBox1.Text = Request.QueryString["Parameter"].ToString();

This is the most reliable way when you are passing integer kind of value or other short parameters. More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:

FirstForm.aspx.cs

Response.Redirect("SecondForm.aspx?Parameter=" + Server.UrlEncode(TextBox1.Text));

SecondForm.aspx.cs

TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());

URL Encoding

  1. Server.URLEncode
  2. HttpServerUtility.UrlDecode

2. Passing value through context object

Passing value through context object is another widely used method.

FirstForm.aspx.cs

TextBox1.Text = this.Context.Items["Parameter"].ToString();

SecondForm.aspx.cs

this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer("SecondForm.aspx", true);

Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.

3. Posting form to another page instead of PostBack

Third method of passing value by posting page to another form. Here is the example of that:

FirstForm.aspx.cs

private void Page_Load(object sender, System.EventArgs e)
{
   buttonSubmit.Attributes.Add("onclick", "return PostPage();");
}

And we create a javascript function to post the form.

SecondForm.aspx.cs

function PostPage()
{
   document.Form1.action = "SecondForm.aspx";
   document.Form1.method = "POST";
   document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();

Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false

4. Another method is by adding PostBackURL property of control for cross page post back

In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.

FirstForm.aspx.cs

<asp:Button id=buttonPassValue style=”Z-INDEX: 102″ runat=”server” Text=”Button”         PostBackUrl=”~/SecondForm.aspx”></asp:Button>

SecondForm.aspx.cs

TextBox1.Text = Request.Form["TextBox1"].ToString();

In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.

You can also use PreviousPage class to access controls of previous page instead of using classic Request object.

SecondForm.aspx

TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1″);
TextBox1.Text = textBoxTemp.Text;

As you have noticed, this is also a simple and clean implementation of passing value between pages.

Reference: MICROSOFT MSDN WEBSITE

HAPPY CODING!

शेखर
  • 17,412
  • 13
  • 61
  • 117
  • I don't know how to write your name, but thanks for the info. I have a method in my Master.Page that gets/sets the User object into a Session variable. After the log in on the Login page that inherits Master.Page, they can send an email using the Contact page that also inherits from Master.Page. However, on Contact page's Page_Load event, the User object is null. I don't know why. –  Apr 29 '16 at 14:27
3

If it's just for passing values between pages and you only require it for the one request. Use Context.

Context

The Context object holds data for a single user, for a single request, and it is only persisted for the duration of the request. The Context container can hold large amounts of data, but typically it is used to hold small pieces of data because it is often implemented for every request through a handler in the global.asax. The Context container (accessible from the Page object or using System.Web.HttpContext.Current) is provided to hold values that need to be passed between different HttpModules and HttpHandlers. It can also be used to hold information that is relevant for an entire request. For example, the IBuySpy portal stuffs some configuration information into this container during the Application_BeginRequest event handler in the global.asax. Note that this only applies during the current request; if you need something that will still be around for the next request, consider using ViewState. Setting and getting data from the Context collection uses syntax identical to what you have already seen with other collection objects, like the Application, Session, and Cache. Two simple examples are shown here:

// Add item to
Context Context.Items["myKey"] = myValue;

// Read an item from the
 Context Response.Write(Context["myKey"]);

http://msdn.microsoft.com/en-us/magazine/cc300437.aspx#S6

Using the above. If you then do a Server.Transfer the data you've saved in the context will now be available to the next page. You don't have to concern yourself with removing/tidying up this data as it is only scoped to the current request.

Sam Shiles
  • 10,529
  • 9
  • 60
  • 72
1

You can assign it to a hidden field, and retrieve it using

var value= Request.Form["value"]
Matt Evans
  • 7,113
  • 7
  • 32
  • 64
1

You can use query string to pass value from one page to another..

1.pass the value using querystring

 Response.Redirect("Default3.aspx?value=" + txt.Text + "& number="+n);

2.Retrive the value in the page u want by using any of these methods..

Method1:

    string v = Request.QueryString["value"];
    string n=Request.QueryString["number"];

Method2:

      NameValueCollection v = Request.QueryString;
    if (v.HasKeys())
    {
        string k = v.GetKey(0);
        string n = v.Get(0);
        if (k == "value")
        {
            lbltext.Text = n.ToString();
        }
        if (k == "value1")
        {
            lbltext.Text = "error occured";
        }
    }

NOTE:Method 2 is the fastest method.

coder
  • 1,980
  • 3
  • 21
  • 32