Several Methods for passing values between ASP. NET pages, asp.net pages

Source: Internet
Author: User
Tags asp net

Several Methods for passing values between ASP. NET pages, asp.net pages
Several Methods for passing values between ASP. NET pages

Page value passing is a problem that will be faced in the early stages of learning asp.net. In general, there are page value passing, storing object Value passing, ajax, class, model, form, and so on. However, in general, QueryString, Session, Cookies, Application, Server. Transfer are commonly used.

 

  I. QueryString

QueryString is a simple method for transferring values. It can display the transmitted values in the address bar of a browser. This method can be used to transmit one or more numeric values with low security requirements or simple structure. However, this method cannot be used to pass arrays or objects.

Advantages of this method: 1. Simple to use, it is very effective to transmit numbers or text values when security requirements are not high.
Disadvantages of this method: 1. Lack of security because its value is exposed in the URL address of the browser.
2. Objects cannot be passed.

Method of use: 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.

Example: (1) a. aspx

private void Button1_Click(object sender, System.EventArgs e) {   string s_url;   s_url = "b.aspx?name=" + Label1.Text;   Response.Redirect(s_url); }

(2) B. aspx

private void Page_Load(object sender, EventArgs e) {   Label2.Text = Request.QueryString["name"]; }

 

  Ii. Session

  Presumably, this is definitely the most common usage. Its operations are similar to those of the Application, which act on individual users. Therefore, excessive storage will result in the depletion of server memory resources.

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 the Session variable will consume a lot of server resources.

2. easy to lose.

Usage: 1. Create the Name and Value you need to pass in the Code on the Source Page to construct the Session variable: Session ["Name"] = "Value (Or Object )";

2. The code on the target page uses the Session variable to retrieve the passed value. Result = Session ["Nmae"]

Note: A session can be destroyed when it is not used. The destroy method is to clear Session. Remove ("session name ");

Clear all: Session. Clear ();

Example: (1) a. aspx

private void Button1_Click(object sender, System.EventArgs e) {   Session["name"] = Label.Text; }

(2) B. aspx

private void Page_Load(object sender, EventArgs e) {   string name;   name = Session["name"].ToString(); }

 

3. Cookie

  This is also a common method. 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.

Like Session, Cookie is stored on the client and session is stored on the server. In addition, the use of cookies should be used in combination with the ASP. NET built-in Object Request.

Advantages: 1. Easy to use, is a very common method 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. Low Security and easy to forge.

  

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;

Example: (1) a. aspx

private void Button1_Click(object sender, System.EventArgs e){  HttpCookie objCookie = new HttpCookie("myCookie","Hello,Cookie!");  Response.Cookies.Add(objCookie); }

(2) B. aspx

string myName1Value;myName1Value = Request.Cookies[ "myCookie" ].Value;

 

  Iv. Application

The scope of the Application object is global, that is, it is valid for all users. It is effective throughout the application lifecycle, similar to using global variables, so it 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.

Some may ask, since all users can use the application variable, where can they be used? Here is an example of the number of website regions. You can perform operations on multiple requests.

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.

Disadvantage: 1. As a global variable, it is prone to misoperations. Therefore, application is generally unavailable for variables used by a single user.

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"]

Note: The lock and unlock methods are often used to lock and unlock, in order to prevent concurrent modification.

Example: (1) a. aspx

private void Button1_Click(object sender, System.EventArgs e) {   Application["name"] = Label1.Text; }

(2) B. aspx

private void Page_Load(object sender, EventArgs e) {   string name;   Application.Lock();   name = Application["name"].ToString();   Application.UnLock(); }

 

  V. Server. Transfer

  This can be said to be the method used for face object development. It uses Server. the Transfer method directs the process from the current page to another page. The new page uses the response stream of the previous page. Therefore, this method is completely object-like and concise and effective.

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.

Ps: Compare the differences between Server. Transfer and Response. Redirect.
(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.

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 client browser 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.

Method of use: 1. In the code on the Source Page, use the Server. Transfer of the Page class to jump to another Page and pass the Page data: Server. Transfer ("B. aspx", "false ").

2. on the target page, use Context. handler to receive data: FormerPage formerPage = (FormerPage) Context. handler; then, use the attributes and methods of formerPage to obtain the value of the previous page, or directly use Context. items ["myParameter"]

Example: (1) a. aspx

public string Name {   get{ return Label1.Text;} } private void Button1_Click(object sender, System.EventArgs e) {   Server.Transfer("b.aspx"); }

(2) B. aspx

Private void Page_Load (object sender, EventArgs e) {a newWeb; // instance a form newWeb = (source) Context. Handler; string name; name = newWeb. Name ;}

 

These are commonly used methods for transferring values between pages. I generally use session and querystring to transfer values. In rare cases, cookies are used. This article only introduces how to use these methods, and does not explain the Internal principles too much. For more information about session storage methods, see session storage methods and configuration.


How do I list the methods for passing values between ASP NET pages?

1. Use QueryString variable
QueryString is a simple method for transferring values. It can display the transmitted values in the address bar of a browser. This method can be used to transmit one or more numeric values with low security requirements or simple structure. However, this method cannot be used to pass arrays or objects. The following is an example:
A. aspx C # code
Private void button#click (object sender, System. EventArgs e)
{
String s_url;
S_url = "B. aspx? Name = "+ Label1.Text;
Response. Redirect (s_url );
}

B. C # code in aspx
Private void Page_Load (object sender, EventArgs e)
{
Label2.Text = Request. QueryString ["name"];
}

2. Use the Application object variable
The scope of the Application object is global, that is, it is valid for all users. The common methods are Lock and UnLock.
A. aspx C # code
Private void button#click (object sender, System. EventArgs e)
{
Application ["name"] = Label1.Text;
Server. Transfer ("B. aspx ");
}

B. C # code in aspx
Private void Page_Load (object sender, EventArgs e)
{
String name;
Application. Lock ();
Name = Application ["name"]. ToString ();
Application. UnLock ();
}

3. Use Session Variables
Presumably, this is definitely the most common usage. Its operations are similar to those of the Application, which act on individual users. Therefore, excessive storage will result in the depletion of server memory resources.
A. aspx C # code
Private void button#click (object sender, System. EventArgs e)
{
Session ["name"] = Label. Text;
}

B. C # code in aspx
Private void Page_Load (object sender, EventArgs e)
{
String name;
Name = Session ["name"]. ToString ();
}

4. Use Cookie object variables
This is also a common method. Like Session, it is for every user, but there is a fundamental difference, that is, cookies are stored on the client, session is stored on the server. In addition, the use of cookies should be used in combination with the ASP. NET built-in Object Request.

A. aspx C # code
Private void button#click (object sender, System. EventArgs e)
{
HttpCookie cookie_name = new HttpCookie (& qu ...... remaining full text>

Several methods for transferring values between ASPNET pages

URL, Session, Cookies, Server. Transfer, Application, and cross-page Transfer.
[Analysis]
This topic examines whether the interviewer's understanding of Multi-page pass-through in ASP. NET is comprehensive. Because the ASP. NET page form is submitted to itself to complete the return function, by default, the POST method cannot be used for multi-page value passing. The analysis of these value passing methods is as follows.
1. URL-based value transfer
This is a classic value passing method. This method is very simple to use, but the passed value is displayed in the address bar of the browser, and the object cannot be passed. Therefore, this method is generally used when the passed value is small and the security requirements are not high. In the *. aspx page development, you can use hyperlink text to transfer values, as shown in the following code.
<Asp: HyperLink runat = "server" ID = "maid"
NavigateUrl = "~ /GetValues. aspx? Urlvalue1 = intel & urlvalue2 = amd "> URL-based value transfer </asp: HyperLink>
The above link will jump to the GetValues. aspx page, and pass the urlvalue1 variable and urlvalue2 variable through URL, whose values are intel and amd respectively. In the *. cs server method, you can also call the Redirect method of the HttpResponse object to Redirect the browser to a new page and pass the value through the URL, as shown in the following code.
Response. Redirect ("~ /GetValues. aspx? Urlvalue1 = intel & urlvalue2 = amd ");
2. Pass the Session Value
This method stores each piece of data in server variables and can transmit a large amount of data, which is highly secure. Therefore, it is often used for user identity verification. However, if the Session variable stores too much data, it will consume too much server resources. programmers should be careful when using it. The usage method is shown in the following code.
Session ["SessionValue"] = "ATI ";
// You can also use index Storage
Session [0] = "ATI ";
// The valid value of the server Method on other pages is as follows:
String str = Session ["SessionValue"]. ToString ();
// You can also use the index to obtain
String str = Session [0]. ToString ();
Session can be shared among multiple pages of the application by name/value pairs until the browsing user closes his browser or server Session times out (configurable, the default value is 20 minutes ).
3. Pass Cookie values
Cookie is a special data storage method, because it stores data in the browser's computer and exists in the disk as a text file. This method is very interesting. Many login systems use cookies to automatically log on to users. That is, the login information of a user login will be written into the Cookie file of the user's computer. The website will automatically read the Cookie for authentication at the next login. Although it is convenient to transmit data through cookies, the storage time can be set freely, but the security is not high, programmers should not rely too much on cookies, but should use a combination of methods to store sensitive data.
The main types of Cookie operations in ASP. NET are located in the System. Web namespace, including HttpCookie, HttpResponse, and HttpRequest. HttpCookie can be used to establish and operate the Security type of an independent Cookie. You can obtain the full text of Http by accessing the Cookies of HttpResponse and HttpRequest.>

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.