Opening overview
For any beginner, the transfer of values between pages is the only way, but it is their difficulties. In fact, for most experts, it is not necessarily difficult.
Recalling the nearly 300 people interviewed in 2016, with interns, fresh graduates, 1-3 years of experience, 3-5 years of experience, 5-10 years of experience, for all interviewers, I almost asked the same question: "Please tell me what you know about the value of the various forms and methods of the page, and explain their principles and processes ", on this question, from everyone's answer, the result is not very ideal, from the kind, most people answer 5 kinds of, very few can answer 8 kinds of, not more than 8 kinds of, but from the depth, very few people can thoroughly analyze the principle and process 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 parses requests, CLR,GC, decompile, etc.).
Broadly, the way to pass between ASP. NET pages can be broadly divided into the following types: request.querystring["name"],request.form ("name"), Session,cookie,cache, Application,server.transfer,database,httpcontext the Item property, Files,database, and so on.
Detailed explanation of each method
First, Request.QueryString
Core code:
protected void Getquerystring_click (object sender, EventArgs e) { string questr = request.querystring["name"]; Response.Write (QUESTR); }
Summarize:
1. Request.QueryString: Gets the collection of HTTP query string variables. There are dual loads, i.e. request.querystring[string name] and request.querystring[int index];
2, Request.QueryString is mainly to get the url "? After the argument, such as Url:a.aspx?name= "queryString", the value of request.querystring["name"] is "queryString".
Second, Request.Form
Core code:
protected void Getquerystring_click (object sender, EventArgs e) { string strqueform = request.form["TextBox1"]; Response.Write (Strqueform); }
Summarize:
1. Request.Form gets a collection of form variables. There are dual loads, i.e. request.form[string name] and Requst.form[int index].
2. Gets the parameter value of the name specified by the form.
Third, Session
1. Session Basic operation
A. Create session
Create session public void CreateSession (string[] arrstr) { //create 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, get the value of session
String getsessionvalue=session["name"]. ToString ();
C, Traverse session
Traverse Session public void GetSession () { IEnumerator sessionenum = Session.Keys.GetEnumerator (); while (Sessionenum.movenext ()) { Response.Write (session[sessionenum.current.tostring ()). ToString () + ";"); } }
D. Clear session, but not end
Clears the session, but does not end the conversation public void Clearsession () { session.clear (); }
E. End Session
End session public void Abandonsession () { Session.Abandon (); }
2. Session data storage form and location
<system.web> <sessionstate mode= "off| inproc| stateserver| SQL Server "cookieless=" True|false "timeout=" number of minutes "stateconnectionstring=" Tcpip=server:port " sqlconnectionstring= "SQL connection string" statenetworktimeout= "number of seconds"/></system.web>
Annotations:
Mode: Indicates setting storage session form and location;
A, off: Disable session;
b, inproc:in process abbreviation, indicating that the session is stored in the IIS process, but note that although the performance is high, but IIS restart is, lost session information; (default value)
C, Sateserver: Store the session in the ASP. NET State Service process (the session state is preserved when the Web application is restarted and the session state can be used for multiple Web servers in the network);
D. Store the session in SQL Server
Cookieless: Setting client storage session form and location
A, true: using the cookieless mode, the client session information is no longer using cookies stored, but it is stored through the URL;
B, false: Use Kookie mode, default value.
Timeout sets the number of minutes after which the server automatically discards session information. The default is 20 minutes;
stateConnectionString sets the server name and port number used when the session information is stored in the State service, for example: "tcpip=127.0.0.1:42424". When the value of mode is StateServer Yes, this property is required. (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 SQL Server;
stateNetworkTimeout settings when the session state is stored using StateServer mode, the TCP/IP connection to the server that stores the state information is disconnected after the number of seconds that the Web server is idle. The default value is 10 seconds;
3. Session principle
Why was the session introduced? As you know, because HTTP is a stateless protocol, the session is making up for this flaw. Of course, the role of the session far more than these, here is not much discussion.
Session in ASP., the client (Goggle,firefox,ie, etc.) and server-side sessions are used to store specific session information and, to be precise, to store specific user information. When the client sends a request to the server, such as the login user ID, the server receives the request, the server side session generates a SessionID associated with the logged-in user, and returns the Sessioid to the client (Goggle,firefox,ie, etc.). At the beginning of a new session, the server stores SessionID as a cookie in the user's browser.
Summarize:
1. Definition: System.Web.SessionState.HttpSessionState page.session//Gets the current Session object provided by ASP.
2. Characteristics:
A, the session Chinese means "session", in ASP. NET, represents a session between the client and server, one of the common sessions in the Web.
B. The session is stored in server-side memory.
C, session can store any type of data, including custom objects.
D, session and session are independent of each other, non-interference.
E, session and cookie pairing use, session on the server side generates SessionID, and return the SessionID to the client (Ie,firefox,google, etc.), the client cookie to store the SessionID, As long as the SessionID cookie is not lost, the session information will not be lost during the whole conversation.
F, the session saved data can be accessed across pages, that is, the cross-page is global.
G, session cannot be accessed across processes, only by users of that session.
H, the session information can be cleared without ending the conversation, that is, call Session.clear ();
I, when the session ends, expires, the server clears the session object.
J, session is often used to save the ID of the logged-on user.
Iv. Application
Core code:
(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 ();}
Summarize:
1. The scope of the Application object is the whole global, which means it is valid for all users. It is valid throughout the application life cycle, similar to using global variables, so it can be accessed from different pages. It differs from the session variable in that the former is a global variable shared by all users, and the latter is a unique global variable for each user. One might ask, since all users can use the application variable, where can he use it? Here's an example: the number of site visits. It can be manipulated when multiple requests are accessed.
2, Advantages: Simple to use, consumes less server resources, not only can pass simple data, but also can pass the object, data volume size is unlimited.
3, disadvantage: As a global variable is easy to operate by mistake. Therefore, the variables used by individual users are generally not application.
4. Create the name and value you need to pass in the source page code to construct the application variable: application["name"]= "value (Or Object)"; The code in the destination page uses the application variable to remove the value passed. Result = application["Name"].
5, the common lock and unlock method is used to lock and unlock, in order to prevent concurrent modification.
Five, Cache
Core code:
Class1 cache["id"] = TextBox1.Text; Response.Redirect ("~/webform1.aspx"); Class2 if (cache["id"]!=null) { Label1.Text = cache["id"]. ToString (); }//Remove cache Cache.remove ("id"); If cache["id"] is empty, the pass value fails. The following method can be used for the actual//period of 10 minutes Cache.Insert ("id", Textbox1.text,null,cache.noabsoluteexpiration,new TimeSpan (0,10,0));
Summarize:
1. The caching mechanism in the application is used to store objects created with a large number of server resources in memory, which greatly improves the performance of the application. This mechanism can also be used to transmit values.
2, unlike other methods, the method needs to set the cache item priority and cache time. Because when system memory is scarce, the caching mechanism automatically removes items that are seldom used or lower in priority, resulting in a failed pass.
3, the advantages of this method is the transmission of data size and quantity of unrestricted, fast. The disadvantage is that the operation of the caching mechanism is relatively complex.
VI. Cookies
Core code:
Class1 HttpCookie HttpCookie = new HttpCookie ("TestCookie", "page transfers by Cookie"); Response.Redirect ("~/class2.aspx");//class2 Label1.Text = request.cookies["TestCookie"]. Value;
Summarize:
1, the cookie is used to store small pieces of information in the user's browser, save the user's relevant information, such as the user's access to a website user ID, user preferences, etc., the next time the user can retrieve the previous information through the search. So cookies can also pass values between pages.
2. The cookie is passed back and forth between the browser and the server via the HTTP header. A cookie can contain only the value of a string, and if you want to store an integer value in a cookie, you need to first convert to a string.
3, as with the session, it is what for each user, but there is an essential difference, that is, the cookie is stored in the client, and the session is stored on the server side. And the use of cookies should be used in conjunction with the ASP.
4, easy to use, is to maintain the user state of a very common method. For example, in a shopping site, users can use it to maintain user status when they cross multiple page forms.
5, is often considered to collect user privacy and has been criticized.
6, security is not high, easy to forge.
VII. context.items["id"]
Core code:
Class1 context.items["id"]=textbox1.text; Server.Transfer ("~/class2.aspx"); CLASS2 label1.text=context.items["id"]. ToString (); Context.Items.Remove ("id"); Remove Item
1. The context object contains information related to the current page, providing access to the entire context, including requests, responses, and information such as the session and application above.
2. You can use this object to share information between pages, thus enabling the transfer of values between pages.
3, similar to the method of using Form, the method can also maintain a large number of data, the shortcomings are the same, but the use of the method is relatively simple.
Eight, ViewState
Core code:
class1viewstate["id"]=textbox1.text; Data save label1.text=viewstate["id"]. ToString (); Data Extraction Viewstate.remove ("id"); Data removal
Summarize:
1. ViewState is a mechanism that ASP. NET uses to save and restore view state of server controls between multiple requests on the same page. Unlike the traditional "same page", every Request for "same page" in ASP. will cause the server to regenerate the page, but the newly generated page does not contain the data from the original page. (page non-stateful)
2, ViewState's task is to save the original page of the server control view state of the data for the new page to use. In this sense, ViewState can also be seen as a tool for passing data between pages.
3, ViewState work principle is: As a hidden form field between the client and the server passed, visible, misuse of ViewState will aggravate the burden of page callbacks, thereby reducing the performance of the application.
In addition, ViewState can be disabled by controls, pages, and applications.
Ix. Web. config and machine.config
Core code:
Class1using System.Web.Configuration; WebConfigurationManager.AppSettings.Set ("UserName", TextBox1.Text); Response.Redirect ("~/class2.aspx");//class2using System.Web.Configuration; Label1.Text = webconfigurationmanager.appsettings["UserName"];
Summarize:
1. Each Web application inherits the settings of the. config file and the Machine.config file.
2. Web. config and machine.config these two files are generally small and clear, especially for storing some string constants, such as database connection information. In addition, the Web. config file can be extended and, therefore, can be used to pass variables. Because these two files are automatically cached, there is no problem with the performance bottleneck caused by disk IO. Note that some settings in the file will cause the file to be modified after the Web application restarts.
3. Web. config: You can apply settings to individual Web applications. For example, you might want to set a specific validation method, the type of debugging, the default language, or the custom error page. However, if you want to use these settings, you must place the Web. config file under the root virtual directory of the application. To further configure your subdirectories in Web applications, you need to place additional Web. config in these folders. (For a detailed description of the ASP. Net. config file, refer to my other blog: ASP. Net. config)
4. Machine.config: Start configuration from a file called Macine.config in the C:\windows\microsoft.net\framework\framework\[version]\config directory. The Machine.config file defines the supported configuration file sections, configures the ASP. NET worker process, and registers the providers that can be used for advanced features such as profiles, membership, role-based security, and so on. (For a detailed introduction to the ASP. machine.config file, I'll write an article about it later)
Ten, Static
Core code:
The static global variable username=txtboxusername.text is defined in the Class1public static string username;//in Class1; Response.Redirect ("~/class2.aspx");//class2label1.text=src.id;
Summarize:
1, this should be very easy to understand, in ASP. NET, each page corresponds to a specific class, so, then the transfer between the pages, we can boil down to: class and class data transfer. Thinking about this step, the problem should be solved, because we can use the public relations between the class static variables to solve the problem.
2, if reasonable use, can effectively improve the efficiency of data transmission, but if abused, may lead to user or page data disorder, there are certain risks and hidden dangers, should be used with caution.
Ask the following questions: Can you analyze what is wrong with the following code?
Class1 protected void Btnredirect_click (object sender, EventArgs e) { string userName = Txtboxusername.text; Response.Redirect ("~/class2.aspx"); } Class2 Lable1.text=username;
Xi. add frequently used pages to jump between
1. The most commonly used page jumps (the original window is replaced): Response.Redirect ("xxx.aspx");
2. Open a local webpage or Internet using the URL address: respose.write ("<script language= ' JavaScript ' >window.open ('" + url+ "');</script>") ;
3. The original window is retained to open another page (the browser may block, need to release): Response.Write ("<script>window.open (' xxx.aspx ', ' _blank ') </script>") ;
4. Another way of writing the effect with 1: Response.Write ("<script>window.location= ' xxx.aspx ' </script>");
5. Also the original window is replaced (often used to pass the session variable page jump): Server.Transfer ("xxx.aspx");
6. Keep the original window, open a new window as a dialog box: Response.Write ("<script>window.showmodelessdialog (' xxx.aspx ') </script>");
7. Open a new window in the form of dialog, the original window is replaced by: Response.Write ("<script>window.showmodeldialog (' xxx.aspx ') </script>");
8. Open the Compact window: Respose.write ("<script language= ' JavaScript ' >window.open ('" +url+ "', ' ', ' resizable=1,scrollbars=0, Status=1,menubar=no,toolbar=no,location=no, Menu=no ');</script> ");
9. Using the VS2008 port: System.Diagnostics.Process.Start (http://localhost:3210/system administrator. aspx);
Note: Relatively simple, I do not discuss here.
Summarize:
About the page transfer value, there are many methods, such as file transfer value, database value, ViewBag and so on, here is a discussion. If there is time later, will be added on this basis, and gradually improve the blog post.
The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support topic.alibabacloud.com.