Several Methods for passing values between ASP. NET pages

Source: Internet
Author: User

Several Methods for passing values between ASP. NET pages...

I. Use querystring

Request. querystring
In the ASP era, this is a commonly used method. net, it seems that there are not many people to use, but in any case, this is not outdated, and it is worth recommending, because either ASP or ASP. net, the most basic is based on the HTTP protocol. The disadvantage is that the request may fail when multiple pages are passed.

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. In the source pageCodeUse the name and value to be passed 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 applicationProgramGlobal settings.
-->
<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
This is still quite common in the ASP era. It is mainly used to store global variables, such as database link information. In the ASP. NET era, there is not much to use, at least I seem to have never used it.
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. The difference between it and session 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 directly used by all pages of the application.
The account name you log on to generally uses the session variable. When multiple requests are accessed, they have their own session variables and can only operate on their own session variables, this variable is directly used on each page of the application 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

This is the most commonly used method. The advantage of session is that it is easy to use, but the disadvantage is that it occupies server resources, because each session means that the server needs to maintain the session information of the corresponding customer, naturally, if there are more login users, the server resources will be very occupied. In addition, the session also has a disadvantage. By default, if you do not perform any action within 20 minutes after logon, the server will automatically cancel the session, so you need to log on again.
PS. This reminds me of one thing. A company showed me a piece of code a few days ago. When I log on, I used session to record user logon. My God, microsoft knows that it must vomit blood !! It has worked hard to provide you with web. the configuration in config <deny user = "*"/> requires this configuration. You don't need to use the session in the ASP era. It's not a waste of Ms painstaking efforts.

Using the application variable is the third way to pass values between pages. Session variables are very similar to Application variables, and their differences have been mentioned above about Application variables.

(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

This is my favorite. The biggest feature of cookie is that it is maintained by the client and does not occupy server resources. You can also set the cookie validity period during user login, such as one day, in this way, you do not have to worry about logging on to the system again within one day. Of course, cookies also have disadvantages, that is, security. Because cookies are on the client, some software can analyze the login information of cookies. Therefore, do not be too sensitive to the content written into cookies, for example, do not store passwords, also, for security purposes, it is best to encrypt the content written into cookies.
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, such as the user ID and user preferences when a user accesses a website, the user can retrieve the previous information from the next visit. Therefore, cookies can also pass values between pages. The cookie is sent back and forth between the browser and the server through the HTTP header. 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 Transfers the current ASPX page to the new ASPX page. The server executes the new page and outputs the new page through context. handler to obtain the values, form data, and querystring of various data types passed on the previous page. because the redirection is completed on the server side, the URL 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 in the client browser will not change; response. redirect is completed by the client and a new page Processing request is submitted to the server, so the URL address in the client browser will change.
(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 address.
(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 to upload various types of values to the 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 the target page are not in the same virtual directory or their sub-directories, images and hyperlinks using relative paths will lead to incorrect pointing. [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 will not be able to obtain various data types or control values on the previous page, because the current page instance is obtained. therefore, the new page (destinationwebform. use if (! Ispostback) contains the code for getting the value of the previous page to obtain the values of various data types, form data, and querystring passed on the previous page.

(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; // obtain the value through the attributes 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 in formerpage.
// The following methods are mostly used for obtaining a value in the control, however, if you assign a value to textbox1.text directly in the program, the following method gets the
// null value. In this case, you need to use the above method
// textboxvalu E = request. form ["textbox1"];
contextitemsvalue = context. items ["newcontext"]. tostring (); // obtain the value through items of context in formerpage
listresult = (arraylist) context. items ["destinationlist"]; // gets the object through the items of context in formerpage. The forced conversion type is:
querystring = request. querystring ["name1"]; // obtain the value from querystring in the URL of formerpage
}< br> catch
{< br> response. write ("error! ");
}< BR >}

Vi. viewstate
Added by ASP. NET, viewstate is easy to use, but its disadvantage is that it can only be used on the same page. In ASP. net2.0, The postbackurl of the button can be used for the result.

VII. Cache
There is not much to think about using the cache to store data, but it is also a method. In addition, when using the cache to store dataset, it is actually a reference instead of a copy of the content.

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.