Several methods for transferring values between ASP. NET pages, asp.net pages

Source: Internet
Author: User

Several methods for transferring values between ASP. NET pages, asp.net pages

Overview

For any beginner, passing values between pages is the only way to go, but it is also their difficulty. In fact, it is not difficult for most experts.

Recall that nearly 2016 people interviewed in 300 have interns, fresh graduates, 1-3 years of experience, 3-5 years of experience, 5-10 years of experience, and all interviewers, I almost asked the same question: "Please refer to several forms and methods for passing values between pages you know,

And explained their principles and processes. "According to your answers, the results are not very satisfactory. In terms of types, most people answer about five questions, A small number of answers can be answered in eight ways, but in depth, few can thoroughly analyze each method.

(Of course, to thoroughly analyze these principles and processes, you need to study the underlying things, such as page lifecycle and page principles, reflection, how IIS parses requests, etc, CLR, GC, decompilation, etc ). In view of this, I will spend some time today to summarize

Everyone learns and makes progress together !!

Ming: This blog only analyzes the breadth, not in depth. If the majority of readers are interested in depth and have certain needs, I wrote a deep analysis article dedicated to sharing, learning, and making progress together.

To sum up, ASP. NET pages can be passed in the following ways: Request. queryString ["name"], Request. form ("name"), Session, Cookie, Cache, Application, Server. transfer, Database,

The Item attribute of HttpContext, Files, DataBase, and so on.

 

Detailed explanation of each method

 

1. Request. QueryString

Core code:

protected void getQueryString_Click(object sender, EventArgs e) {      string QueStr = Request.QueryString["name"];      Response.Write(QueStr); }

Summary:

1. Request. QueryString: Get the http query string variable set. There are two reloads: Request. QueryString [string name] and Request. QueryString [int index];

2. Request. QueryString is mainly used to obtain "?" in the url. The following parameter, such as url: a. aspx? Name = "queryString", the value of Request. QueryString ["name"] is "queryString ".

 

Ii. Request. Form

Protected void getQueryString_Click (object sender, EventArgs e) {string strQueForm = Request. Form ["TextBox1"]; Response. Write (strQueForm );}

Summary:

1. Request. Form: Get the Form variable set. There are two reloads: Request. Form [string name] And Requst. Form [int index].

2. Obtain the parameter value of the specified form name.

 

Iii. Session

// Create Session public void createSession (string [] arrStr) {// create an array string [] str = new string [arrStr. length]; for (int I = 0; I <arrStr. length; I ++) {str [I] = I. toString (); Session [str [I] = arrStr [I] ;}}

B. Obtain the Session value.

string  getSessionValue=Session["name"].ToString();

C. Traverse sessions

// Traverse the Session public void getSession () {IEnumerator sessionEnum = Session. keys. getEnumerator (); while (sessionEnum. moveNext () {Response. write (Session [sessionEnum. current. toString ()]. toString () + ";");}}

D. Clear the Session, but do not end the Session

// Clear the Session, but do not end the Session public void clearSession () {Session. Clear ();}

E. End Session

// End the Session public void abandonSession () {Session. Abandon ();}

2. Session data storage format and location

<system.web>  <sessionState mode="Off|InProc|StateServer|SQLServer"  cookieless="true|false"  timeout="number of minutes"  stateConnectionString="tcpip=server:port"  sqlConnectionString="sql connection string"  stateNetworkTimeout="number of seconds"/></system.web>

Note:

Mode: Specifies the format and location of the stored Session;

A. Off: Disable Session;

B. Inproc: In Process abbreviation, indicating that sessions are stored In IIS processes. However, although the performance of this method is high, the Session information is lost when IIS is restarted. (default)

C. SateServer: stores sessions in ASP. NET state service processes (the Session state is retained when the Web application is restarted, and the Session state can be used by multiple Web servers on the network );

D. Store sessions in SQL Server

Cookieless: sets the format and location of the Session stored on the client.

A. true: In cookieless mode, the Session information of the client is no longer stored using cookies, but stored through URLs;

B. false: The default value is kookie.

Timeout specifies the number of minutes after which the server automatically waives the Session information. The default value is 20 minutes;

StateConnectionString is the name and port number of the server used to store Session information in the status service, for example, "tcpip = 127.0.0.1: 42424 ". This attribute is required when the mode value is StateServer. (Default port 42424 );

SqlConnectionString sets the connection string when connecting to SQL Server. For example, "data source = localhost; Integrated Security = SSPI; Initial Catalog = joye ". This attribute is required when the mode value is SQLServer;

StateNetworkTimeout sets the number of seconds after the Session state is stored in StateServer mode and the TCP/IP connection between the Web server and the server that stores the status information. The default value is 10 seconds;

3. Session Principle

Why is Session introduced? As we all know, because http is a stateless protocol, Session is making up for this defect. Of course, the role of Session is far more than that, and we will not discuss it here.

In ASP. NET, Session indicates the Session between the client (Goggle, Firefox, IE, etc.) and the server, which is used to store specific Session information. Specifically, Session is used to store specific user information. When a client sends a request to the server, such as the Login User ID, the server receives the request, the server Session generates a SessionID related to the login user, and return SessioID to the client (Goggle, Firefox, IE, etc.). At the beginning of the new session, the server stores SessionID as a cookie in the user's browser.

Summary:

1. Definition: System. Web. SessionState. HttpSessionState Page. Session // obtain the current Session object provided by ASP. NET.

2. features:

A. Session indicates the Session between the client and the server in ASP. NET. It is one of the common web sessions.

B. sessions are stored in the server memory.

C. Sessions can store any type of data, including custom objects.

D. The Session and Session are independent of each other and do not interfere with each other.

E. Session is paired with Cookie. Session generates a SessionID on the server and returns the SessionID to the client (IE, FireFox, Google, etc.). The client Cookie stores the SessionID,

During the whole Session process, Session information will not be lost as long as the Cookie for saving the SessionID is not lost.

F. Data stored in sessions can be accessed across pages, that is, cross pages are global.

G. The Session cannot be accessed across processes and can only be accessed by the Session user.

H. You can Clear the Session information without terminating the Session, that is, call Session. Clear ();

I. When the Session ends and expires, the server will clear the Session object.

J. Session is often used to save the Login User ID.

 

Iv. Application

Private void button#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(); }

Summary:

1. 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 you can

Access it. 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. Someone may ask, since all users can use the application

Variable. Where can it be used? Here is an example of the number of website regions. You can perform operations on multiple requests.

2. advantages: it is easy to use and consumes less server resources. It can not only transmit simple data, but also transmit objects. The data size is unlimited.

3. disadvantage: as a global variable, misoperations are easy. Therefore, application is generally unavailable for variables used by a single user.

4. Create the name and Value you need to pass in the Code on the Source Page to construct the Application variable: Application ["name"] = "Value (Or Object )"; the code on the target page uses the Application variable to retrieve the passed value. Result = Application ["name"].

5. The lock and unlock methods are commonly used to lock and unlock. To prevent concurrent modification.

 

V. Cache

// Class1 Cache ["id"] = TextBox1.Text; Response. Redirect ("~ /WebForm1.aspx "); // Class2if (Cache [" id "]! = Null) {Label1.Text = Cache ["id"]. toString ();} // remove the Cache. remove ("id"); // If the Cache ["id"] is empty, the value fails to be passed. You can use the following method to implement the Cache. Insert ("id", TextBox1.Text, null, Cache. NoAbsoluteExpiration, new TimeSpan (, 0 ));

Summary:

1. the cache mechanism in applications is used to store objects that require a large amount of server resources in the memory, thus greatly improving the application performance. This mechanism can also be used to pass values.

2. Unlike other methods, This method requires setting the cache item priority and cache time. When the system memory is insufficient, the cache mechanism will automatically remove items that are rarely used or have a lower priority, resulting in a failed value transfer.

3. The advantage of this method is that the size and quantity of transmitted data are unlimited and the speed is fast. The disadvantage is that the operation of the cache mechanism is relatively complicated.

 

Vi. Cookie

// Class1HttpCookie httpCookie = new HttpCookie ("testCookie", "Page transfers by Cookie"); Response. Redirect ("~ /Class2.aspx "); // Class2Label1. Text = Request. Cookies [" testCookie "]. Value;

Summary:

1. 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 data by accessing

Obtain previous information. Therefore, cookies can also pass values between pages.

2. 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.

3. Just like Session, it is for every user, but there is an essential difference: Cookie is stored on the client, and session is stored on the server. And Cookie enabling

It must be used with the ASP. NET built-in Object Request.

4. 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.

5. People are often criticized for collecting user privacy.

6. Low Security and easy forgery.

 

VII. Context. Items ["id"]

// Class1 Context. Items ["id"] = TextBox1.Text; Server. Transfer ("~ /Class2.aspx ");
// Class2 Label1.Text = Context. Items ["id"]. ToString (); Context. Items. Remove ("id"); // Remove an item

1. The Context object contains information related to the current page and provides access to the entire Context, including the request, response, and Session and Application information in the preceding section.

2. You can use this object to share information between webpages so as to transmit values between pages.

3. Similar to the Form method, this method can maintain a large amount of data with the same disadvantages, but the method is relatively simple.

 

8. ViewState

// Class1ViewState ["id"] = TextBox1.Text; // save Label1.Text = ViewState ["id"]. toString (); // retrieve the ViewState data. remove ("id"); // Remove data

Summary:

1. ViewState is a mechanism used by ASP. NET to save and restore the view status of server controls between multiple requests on the same page. Unlike the traditional "Same page ",

Every request causes the server to regenerate the page, but the newly generated page does not contain the data of the original page. (Stateless page)

2. The ViewState task is to save the Server Control view status data on the original page for use on the new page. In this sense, ViewState can also be seen as a tool for transferring data between pages.

3. ViewState is transmitted between the client and the server as a hidden form field. It can be seen that misuse of ViewState will increase the burden of page return and thus reduce application performance.

In addition, ViewState can be disabled by controls, pages, and applications.

 

9. web. config and machine. config

// Class1using System. Web. Configuration; WebConfigurationManager. deleettings. Set ("userName", TextBox1.Text); Response. Redirect ("~ /Class2.aspx "); // Class2using System. Web. Configuration; Label1.Text = WebConfigurationManager. etettings [" userName "];

Summary:

1. Each Web application inherits the settings of the web. config file and the machine. config file.

2. The data stored in web. config and machine. config files is usually very small and mostly plain text. It is especially suitable for storing string constants, such as database connection information. In addition, the web. config file can be

Therefore, it can also be used to pass variables. Because these two files are automatically cached, there is no performance bottleneck caused by disk IO. Note that some settings in the file will cause the file to be modified

Web application restart.

3. web. config: You can apply settings to a single Web application. For example, you may want to set a specific verification method, debugging type, default language, or custom error page. But if you want to use these

You must put the web. config file in the root virtual directory of the web application. To further configure your sub-directories in the Web application, you need to add web. config to these folders.

(For details about the ASP. NET web. config file, refer to my other blog: ASP. NET web. config)

4. machine. config: Start configuration from a file named macine. Config in the c: \ Windows \ Microsoft. NET \ Framework \ [Version] \ config directory. Machine. config

The file defines the Supported configuration file section, configures ASP. NET worker processes, and registers can be used for advanced features (such as configuration files, membership, and role-based security) providers. (About ASP. NET machine. config

A detailed introduction to the file. I will write an article to introduce it later)

 

10. Static

// Class1public static string userName; // defines the static global variable userName = txtBoxUserName. Text in class1; Response. Redirect ("~ /Class2.aspx "); // class2Label1. Text = Src. id;

Summary:

1. This should be very easy to understand. In ASP. in. NET, each page corresponds to a specific class. In this case, the transfer between pages can be attributed to the transfer of data between classes. The question should be

We can solve this problem by Using PR static variables between classes.

2. Reasonable Use of data can effectively improve data transmission efficiency. However, misuse of data may cause data disorder between users or pages, which may cause some risks and risks. Therefore, use it with caution.

Ask the following question: can you analyze the following code?

//Class1 protected void btnRedirect_Click(object sender, EventArgs e)        {                         string userName = txtBoxUserName.Text;            Response.Redirect("~/Class2.aspx");        }//Class2Lable1.Text=userName;

11. Supplement common page jumps

Note: It is relatively simple. I will not discuss it here.

Summary:

There are many other methods for transferring values between pages, such as file transfer, database transfer, and ViewBag, which will not be discussed here. If you have time in the future, we will add this post on this basis and gradually improve this blog.

 

 

 

Note: I am very grateful for your reading and comments. Some readers have suggested that some content in this article should not be classified as inter-page values, such as web. config and databases. About this

I think everyone has their own standards for transferring values between pages. The results should be different if the standards are different.

In this blog post, I have defined cross-page value transfer as follows. "cross-page value transfer" means that parameters and data can be transmitted between pages, not

In some textbooks, the definition of Inter-page value transfer is dead. My definition is based on actual problems and can actually solve cross-page value transfer, that is, as long as the value can be transferred between pages

To pass values between pages.

 

 

 

  • Thank you for your reading. If you have any shortcomings, please kindly advise and learn and make progress together.
  • Blog website: http://www.cnblogs.com/wangjiming /.
  • A small number of articles are integrated by reading, referencing, referencing, copying, copying, and pasting. Most of them are original articles.
  • If you like, please recommend it; if you have new ideas, welcome to raise, mailbox: 2016177728@qq.com.
  • This blog can be reposted, but it must be a famous blog source.

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.