SoFunction
Updated on 2025-03-07

Detailed explanation of several ways to pass values ​​between pages

Opening overview

For any beginner, passing values ​​between pages is a must, but it is also their difficulty. In fact, for most experts, it may not be a difficult point.

Looking back at the nearly 300 people interviewed in 2016, there were interns, fresh graduates, 1-3 years of experience, 3-5 years of experience, and 5-10 years of experience. For all interviewers, I almost asked the same question: "Please talk about the several forms and methods of passing values ​​between pages you know, and explain their principles and processes." Regarding this question, from everyone's answers, the result is not very ideal. In terms of type, most people answer about 5 kinds, and very few can answer 8 kinds, and there are not more than 8 kinds, but in terms of depth, few people can thoroughly analyze the principles and processes of each method (of course, to thoroughly analyze these principles and processes, you need to study the underlying things, such as page life cycle and page principle, reflection, how IIS resolves requests, etc., CLR, GC, decompilation, etc.).

To summarize, the ways of passing between pages can be roughly divided into the following types: ["name"], ("name"), Session, Cookie, Cache, Application, Database, HttpContext Item properties, Files, DataBase, etc.

Explain each method in detail

one,

Core code:

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

Summarize:

1.: Get the set of http query string variables. There are two overloads, namely [string name] and [int index];

2. Mainly obtain the parameters after "?" in the url, such asurl:?name="queryString", then the value of ["name"] is "queryString".

two,

Core code:

protected void getQueryString_Click(object sender, EventArgs e)
 {
   string strQueForm = ["TextBox1"];
   (strQueForm);
 }

Summarize:

1. Get the form variable collection. There are two overloads, namely [string name] and [int index].

2. Get the parameter value of the name specified in the form.

III. Session

1. Basic Session Operation

a. Create a Session

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

b. Get the value of the Session

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

c. Traversal Session

//Travel the Session    public void getSession()
    {
      IEnumerator sessionEnum = ();
      while (())
      {
        (Session[()].ToString()+";");
      }
    }

d. Clear the Session, but not end the session

//Clear the Session but not end the session    public void clearSession()
    {
      ();
    }

e. End Session Session

//End Session Session    public void abandonSession()
    {
      ();
    }

2. Session data storage form and location

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

annotation:

mode: indicates the setting of the storage session form and location;

a. Off: Disable Session;

b. Inproc:In Process abbreviation means storing the Session in the IIS process. However, note that although this method has high performance, IIS restart is to lose Session information; (default value)

c. SateServer: Store the Session in the state service process (remaining the session state when restarting the web application, and making the session state available for multiple web servers in the network);

d. Store Session in SQL Server

cookieless: Set the client storage session form and location

a. true: Use cookieless mode, and the client's Session information is no longer stored using cookies, but is stored through the URL;

b. false: Use kookie mode, default value.

timeout Sets how many minutes the server automatically abandons the Session information. The default is 20 minutes;

stateConnectionString Sets the server name and port number used when storing Session information in the state service, for example: "tcpip=127.0.0.1:42424". This property is required when the value of mode 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 property is required when the value of mode is SQLServer;

stateNetworkTimeout Sets how many seconds to disconnect the TCP/IP connection between the web server and the server that stores the status information after the state server is idle. The default value is 10 seconds;

3. Session principle

Why introduce Session? As we all know, because http is a stateless protocol, Session is making up for this flaw. Of course, the role of Session is far more than this, so I won't discuss it here.

Session is used to store specific session information. To be precise, it is used to store specific user information. When the client sends a request to the server, such as login user ID, the server receives the request, and the server side Session generates a SessionID related to the login user and returns the SesioID to the client (Goggle, Firefox, IE, etc.). At the beginning of the new session, the server stores the SessionID as a cookie in the user's browser.

Summarize:

1. Definition: //Get the provided current Session object.

2. Features:

a. Session means "session" in Chinese. In it, it represents a session between the client and the server, one of the commonly used sessions in the web.

b. Session is stored in server memory.

c. Session can store any type of data, including custom objects.

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

e. Session is paired with cookies. Session generates a SessionID on the server side and returns the SessionID to the client (IE, FireFox, Google, etc.). The client cookie stores the SessionID. During the entire session, as long as the cookie that saves the SessionID is not lost, the Session information will not be lost.

f. The data saved by Session can be accessed across pages, that is, across pages is global.

g. Session cannot be accessed across processes and can only be accessed by the user of this session.

h. Session information can be cleared without ending the session, that is, call ();

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

j. Session is often used to save the ID of the logged-in user.

IV. Application

Core code:

 (1)

private void Button1_Click(object sender,  e) 
{ 
Application["name"] = ; 
}

(2)

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

Summarize:

1. The scope of the application object is the entire global, which means it is valid for all users. It is valid throughout the application lifecycle, similar to using global variables, so it can be accessed on different pages. The difference between it and the Session variable is that the former is a global variable shared by all users, and the latter is a global variable unique to each user. Some people may ask, since all users can use the application variable, what occasion can they use? Here is an example: website visits. It can be operated on multiple requests for access.

2. Advantages: Simple to use and consume less server resources; it can not only pass simple data, but also object; the amount of data is not limited.

3. Disadvantages: As a global variable, it is easy to be misoperated. Therefore, variables used by a single user cannot be used in general.

4. Create the name and value you need to pass in the code of the source page. Construct the Application variable: Application["name"]="Value(Or Object)"; The code on the destination page uses the Application variable to retrieve the passed value. Result = Application["name"].

5. Common lock and unlock methods are used to lock and unlock to prevent concurrent modifications.

V. Cache

Core code:

//Class1

 Cache["id"] = ;
 ("~/");

//Class2

if (Cache["id"]!=null)
 {
    = Cache["id"].ToString();
 }

//Remove cache("id");

//If Cache["id"] is empty, the value transmission fails.  The following method can be used to implement//The deadline is 10 minutes ("id",,null,,new TimeSpan(0,10,0));

Summarize:

1. The caching mechanism in the application is used to store objects that require a large number of server resources to create in memory, thereby greatly improving the performance of the application. This mechanism can also be used to pass values.

2. Unlike other methods, this method requires setting cache item priority and cache time. Because when the system memory is lacking, the cache mechanism will automatically remove items that are rarely used or have lower priority, resulting in the value transmission failure.

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

VI. Cookies

Core code:

//Class1

HttpCookie httpCookie = new HttpCookie("testCookie","Page transfers by Cookie");
("~/");
//Class2

 = ["testCookie"].Value;

Summarize:

1. Cookies are used to store small pieces of information on the user's browser and save the user's relevant information, such as the user's ID when the user visits a certain website, the user's preferences, etc. The user can obtain the previous information through retrieval the next time he visits. So cookies can also pass values ​​between pages.

2. Cookies are passed back and forth between the browser and the server through HTTP headers. A cookie can only contain the value of a string. If you want to store integer values ​​in a cookie, you need to convert it to the form of a string first.

3. Like Session, it is for every user, but there is an essential difference, that is, cookies are stored on the client, while sessions are stored on the server. Moreover, the use of cookies should be used in conjunction with the built-in object Request.

4. Simple use is a very common method to maintain the user's status. For example, when users form multiple pages in shopping websites, they can use it to maintain the user's status.

5. It is often criticized for being used to collect user privacy.

6. It is not very safe and easy to forge.

7. ["id"]

Core code:

//Class1

 ["id"]=;
 ("~/");

//Class2
 =["id"].ToString();
 ("id"); //Remove item

1. The Context object contains information related to the current page and provides access to the entire context, including requests, responses, and information such as Session and Application above.

2. This object can be used to share information between web pages to achieve the transmission of values ​​between pages.

3. Similar to the method of using Form, this method can also maintain a large amount of data, and its disadvantages are the same, but the usage method is relatively simple.

8. ViewState

Core code:

//Class1
ViewState["id"]=; //Save data=ViewState["id"].ToString(); //Data extraction("id"); //Data removal

Summarize:

1. ViewState is a mechanism used to save and restore the server control view state between multiple requests on the same page. Unlike the traditional "same page", each request for the "same page" in the "same page" will cause the server to regenerate the page, but the newly generated page does not contain the data of the original page. (Page stateless)

2. The task of ViewState is to save data in the server control view status in the original page for use by the new page. In this sense, ViewState can also be regarded as a tool for passing data between pages.

3. The working principle of ViewState is: as a hidden form field is passed between the client and the server. It can be seen that abuse of ViewState will increase the burden of page backloads, thereby reducing the performance of the application.

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

Nine, and

Core code:

//Class1
using ;
("userName",);
("~/");
//Class2
using ;
 = ["userName"];

Summarize:

1. Each web application inherits files and file settings.

2. The data saved by these two files is generally very small, mostly in plain text, which is especially suitable for saving some string constants, such as database connection information. In addition, files can be extended and therefore can also be used to pass variables. Since these two files will be cached automatically, there are no performance bottlenecks caused by disk IO. It should be noted that some settings in the file will cause the web application to restart after the file is modified.

3.: You can apply settings to a single web application. For example, you might want to set a specific verification method, debug type, default language, or custom error pages. But if you want to use these settings, you must put the file in the root virtual directory of the web application. To further configure your own subdirectories in a web application, you need to place additional ones in these folders. (For detailed introduction to the document, please refer to my other blog: )

4.: Start configuration from a file called in the c:\Windows\\Framework\Framework\[Version]\Config directory. File definitions support profile sections, configure worker processes, and register providers that can be used for advanced features such as configuration files, membership, and role-based security. (I will write an article to introduce the detailed introduction of the document later)

10. Static

Core code:

//class1
public static string userName;//Define static global variables in class1userName=;
("~/");
//class2
=;

Summarize:

1. This should be very easy to understand. In this case, each page corresponds to a specific class. Since this is the case, the transfer between pages can be summarized as: the transfer of data between classes. Thinking of this step, the problem should be solved, because we can use static PR variables between classes to solve this problem.

2. If used reasonably, data transmission efficiency can be effectively improved, but if abused, it may lead to data disorder between users or pages, pose certain risks and hidden dangers, and should be used with caution.

Ask the following question: You can analyze what is wrong with the following code?

//Class1

 protected void btnRedirect_Click(object sender, EventArgs e)
    {
       
      string userName = ;
      ("~/");
    }

//Class2

=userName;

11. Jump between supplementary commonly used pages

1. The most commonly used page jump (the original window is replaced): ("");

2. Use the url address to open the local web page or the Internet: ("<script language='javascript'>('"+ url+"');</script>");

3. The original window remains and open another page again (the browser may block it and needs to be uninstalled): ("<script>('','_blank')</script>");

4. Another way to write the same effect as in 1: ("<script>=''</script>");

5. It is also replaced by the original window (often used to pass session variable page jump): ("");

6. The original window is retained and a new window is opened in the form of a dialog box: ("<script>('')</script>");

7. Open a new window in the form of a dialog box, and the original window is replaced: ("<script>('')</script>");

8. Open a simple window: ("<script language='javascript'>('"+url+"','','resizable=1,scrollbars=0,status=1,menubar=no,toolbar=no,location=no,menu=no');</script>");

9. Utilize vs2008 port: (http://localhost:3210/System Administrator.aspx);

Note: It's relatively simple, I won't discuss it here.

Summarize:

There are many other methods about passing values ​​between pages, such as file values, database values, ViewBag, etc., which I will not discuss them one by one here. If you have time in the future, you will supplement it on this basis and gradually improve the blog post.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.