[C #. Net] Passing querystring \ Application \ Session \ cookie to parameters between pages in ASP. NET

Source: Internet
Author: User

I. Use querystring
Using querystring to pass values between pages is a very common method, which is often used in ASP.

(1) advantages and disadvantages
Advantages:
1. Easy to use. It is very effective for passing numbers or text values when security requirements are not high.
Disadvantages:
1. Lack of security because its value is exposed in the URL address of the browser.
2. Objects cannot be passed.

(2) Usage
1. Use the name and value to be passed in the Code on the Source Page to construct the URL address.
2. Use response. Redirect (URL); to redirect the code on the source page to the above URL.
3. Use request. querystring ["name"]; In the code on the target page to retrieve the value passed in the URL address.

(3) Application Example

1. Source Page *. aspx code:

Private void button#click (Object sender, system. eventargs E)
{
String urladdress;
String name1;
String name2;
String name3;
String name1value = "helloname1 ";
Int name2value = 1234567;
String name3value = "Hello name 3 ";

Urladdress = "destinationwebform. aspx? Name1 = "+ name1value +" & "+" name2 = "+ name2value. tostring () +" & "+" name3 = "+

Name3value;
Response. Redirect (urladdress );
}

2. destinationwebform. aspx code on the target page:
Private void page_load (Object sender, system. eventargs E)
{
String myname1value;
Int myname2value;
String myname3value;

Myname1value = request. querystring ["name1"];
Myname2value = convert. toint32 (request. querystring ["name2"]);
Myname3value = request. querystring ["name3"];
}

(4) Possible Problems
1. When the resonse. querystring function transmits Chinese character parameters, an error occurs that the specific value of the parameter cannot be completely passed. There are two solutions.

Method 1: You need to reset encoding and globalization settings in Web. config.

1. First line: <? XML version = "1.0" encoding = "UTF-8"?>
Changed:
<? XML version = "1.0" encoding = "gb2312"?>
2. <! -- Globalization
This section sets the global settings of the application.
-->
<Globalization
Requestencoding = "UTF-8"
Responseencoding = "UTF-8"
/>
Changed:
<! -- Globalization
This section sets the global settings of the application.
-->
<Globalization
Requestencoding = "gb2312"
Responseencoding = "gb2312"
/>
[1]

Method 2: Use server. urlencode and server. urldecode to encode and decode Chinese characters or special characters.

2. Use the application variable

Using the application variable is the second way to pass values between pages.
Application variables are valid throughout the application lifecycle, similar to using global variables, so they can be accessed on different pages. It and session

The difference between variables is that the former is a global variable shared by all users, and the latter is a global variable unique to each user.
For example:
The counter variable for Website access generally uses the application variable. When multiple requests access this variable, you can operate on it. This variable can be

Pages.
The account name you log on to generally uses the session variable. When multiple requests are accessed, they have their own session variables. You can only operate on the session variables of the entire application.

This variable is directly used on each page to obtain basic user information.

(1) advantages and disadvantages

Advantages:
1. Simple to use and consume less server resources.
2. Not only simple data can be passed, but also objects can be passed.
3. The data size is unlimited.

Disadvantages:
1. Global variables are prone to misoperations.

(2) Usage

1. Create the name and value you need to pass in the Code on the Source Page to construct the application variable: application ["nmae"] = "value (or object )";
2. The code on the target page uses the application variable to retrieve the passed value. Result = application ["nmae"]

(3) Application Example

1. Source Page *. aspx code:

Private void button#click (Object sender, system. eventargs E)
{
String name1value = "helloname1 ";
Int name2value = 1234567;

Application ["name1"] = name1value;
Application ["name2"] = name2value;
}

2. Target page *. aspx code:

Private void page_load (Object sender, system. eventargs E)
{
String myname1value;
Int myname2value;

Myname1value = application ["name1"]. tostring ();
Myname2value = (INT) application ["name2"];
}

Iii. Use session Variables

Using the application variable is the third way to pass values between pages. Session variables are very similar to Application variables. Their differences are also described above.

Application variable.

(1) advantages and disadvantages
Advantages:
1. Simple to use, not only can pass simple data types, but also can pass objects.
2. The data size is unlimited.

Disadvantages:
1. storing a large amount of data in session variables will consume a lot of server resources.

(2) Usage

1. Create the name and value you need to pass in the Code on the Source Page to construct the session variable: session ["nmae"] = "value (or object )";
2. The code on the target page uses the session variable to retrieve the passed value. Result = session ["nmae"]

(3) Application Example

Similar to the application variable, you only need to replace the application with the session variable.

Iv. Use cookie objects

Cookie objects are the fourth way to pass values between pages. Cookies are used to store small pieces of information in a user's browser and store user-related information. For example, a user accesses a website.

User ID, user preferences, etc. The user can retrieve the previous information during the next visit. Therefore, cookies can also pass values between pages. Cookie in the browser through the HTTP Header

And the server. A cookie can only contain string values. If you want to store an integer value in a cookie, you must first convert it to a string.
You can retrieve all the cookies of all browsers by traversing the cookie set of the request object. The method is as follows:
Foreach (string strkey in request. Cookies)
{
Lblcookies. Text + = strkey + "=" + request. Cookies [strkey]. value;
}

(1) advantages and disadvantages

Advantages:
1. Easy to use, is a very common way to maintain the user status. For example, you can use a shopping website to maintain the user status when a user spans multiple page forms.

Disadvantages:
1. People are often criticized for being used to collect user privacy.

(2) Usage

1. Create the name and value you need to pass in the Code on the Source Page to construct the cookie object:
Httpcookie objcookie = new httpcookie ("mycookie", "Hello, Cookie! ");
Response. Cookies. Add (cookie );
2. The code on the target page uses the cookie object to retrieve the passed value: Result = request. Cookies ["mycookie"]. value;

(3) Application Example

1. Source Page *. aspx code:

Private void button#click (Object sender, system. eventargs E)
{
Httpcookie objcookie = new httpcookie ("mycookie", "Hello, Cookie! ");
Response. Cookies. Add (objcookie );
}

2. Target page *. aspx code:

Private void page_load (Object sender, system. eventargs E)
{
String myname1value;
Myname1value = request. Cookies ["mycookie"]. value;
}

5. Use server. Transfer

Using the server. Transfer variable is the fifth way to pass values between pages. The above four methods are often used in ASP, but this method is newly introduced in ASP. NET.

. Server. transfer is to switch from the current ASPX page to the new ASPX page. The server executes the new page and outputs it. In the new page, context. handler is used to obtain the previous page transfer.

Values of various data types, form data, and querystring. Because the redirection is completed on the server side, the URL address in the client browser will not change.
When server. Transfer is called, the current ASPX page is terminated and the execution process is transferred to another ASPX page. However, the new ASPX page still uses the response stream created on the previous ASPX page.

[2]

Here we will compare the differences between server. Transfer and response. Redirect used in "1.
(1) server. Transfer is completed on the server, so the URL address in the browser of the client will not change; response. Redirect is completed on the client, and it is proposed to the server

The URL address in the browser of the client changes.
(2) The server. Transfer is completed on the server without the need for a request from the client. This reduces the number of requests sent from the client to the server. [2]
(3) server. Transfer can only jump to the page specified by the local virtual directory, that is, the page in the project, while response. Redirect is very flexible and can jump to any

URL.
(4) server. Transfer can upload values of the previous page to the new page. response. Redirect can only use parameters in the URL or the above four methods.

Upload values of various types to a new page.

Continue to our server. Transfer usage.

(1) advantages and disadvantages

Advantages:
1. Direct redirection on the server side, which is easy to use and reduces the number of requests sent from the client to the server.
2. Various data types and control values can be passed.

Disadvantages:
1. the URL address in the browser on the client is unchanged, which may cause unexpected problems on the new page. For example, if the source page and target page are not in the same virtual directory

Or its subdirectories. [3]

(2) Usage

1. In the code on the Source Page, use the server. Transfer of the page class to jump to another page to transfer page data:
Server. Transfer ("destinationwebform. aspx", "false ").

2. Use context. Handler to receive data on the target page:
Formerpage = (formerpage) Context. Handler;
Then, use the formerpage attributes and methods to obtain the value of the previous page, or directly use
Context. items ["myparameter"]
To obtain the value of the previous page.

It must be noted that these values can be obtained correctly for various data types or control values on the previous page only when the new page is loaded for the first time. In the future PostBack, you cannot

Obtains the values of various data types or controls on the previous page. Because the current page instance is obtained, page_load of the new page (destinationwebform. aspx) is required.

() Use if (! Ispostback) contains the code to get the value of the previous page, in order to get the values of various data types, form data,

Querystring.

(3) Application Example

1. formerpage. aspx code on the Source Page:

Public String hellocontextattribute
{
Get
{
Return "use attribute: Hello, context ";
}
}
Public String hellocontextmethod ()
{
Return "Call method: Hello, context! ";
}

Public String textboxvalue
{
Get
{
Return textbox1.text;
}
}

Private void button#click (Object sender, system. eventargs E)
{
String name1value = "Hello, name1! ";
Textbox1.text = "Hello, textbox1! ";

Arraylist mylist = new arraylist (3); // create a dynamic array
Mylist. Add ("Hello, array1! "); // Add a new value to the dynamic array
Mylist. Add ("Hello, array2! ");
Mylist. Add ("Hello, array3! ");
// Context can store any data type. The context dictionary is specific to an HTTP request.
// Different clients have different values.
Context. items ["destinationlist"] = mylist; // Save the dynamic array in context. Items

Context. Items. Add ("newcontext", "Hello, newcontext"); // save a group of name-value data in context. Items

// If the second parameter of server. Transfer is true, the value of form and querrystring on this page continues to be valid on the new page.
// Otherwise, the textbox1 value cannot be obtained on the new page.
Server. Transfer ("destinationwebform. aspx? Name1 = "+ name1value, true );
}

2. destinationwebform. aspx code on the target page:

Private void page_load (Object sender, system. eventargs E)
{
If (! Ispostback)
{
Try
{
String hellocontextattribute;
String hellocontextmethod;
String textboxvalue;
String contextitemsvalue;
String querystring;

Arraylist listresult;

Formerpage = (formerpage) Context. Handler;
Hellocontextattribute = formerpage. hellocontextattribute; // get the value through the attribute defined in formerpage
Hellocontextmethod = formerpage. hellocontextmethod (); // obtain the value through the method defined in formerpage
Textboxvalue = formerpage. textboxvalue; // return the value of the text control through formerpage
// The following methods are mostly used for obtaining a value after you enter a value in the control, but assign a value to textbox1.text directly in the program.
// Null value. In this case, use the above method.
// Textboxvalue = request. Form ["textbox1"];

Contextitemsvalue = context. items ["newcontext"]. tostring (); // obtain the value through items of context in formerpage
Listresult = (arraylist) Context. items ["destinationlist"]; // obtain the object through the items of context in formerpage. The forced conversion type is as follows:
Querystring = request. querystring ["name1"]; // obtain the value through querystring in the URL of formerpage
}
Catch
{
Response. Write ("error! ");
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.