ASP. NET web forms provides developers with an event-driven development model. However, this simple Program development mode brings us some minor problems. For example, in traditional ASP applications, you can easily transfer one or more values from one page to another through the POST method, and use the same method in ASP. net. Here, we can solve this problem in other ways. ASP. NET provides three methods for us. One is to use querystring to transmit the corresponding value, the other is to transmit the corresponding value through the session variable, and the other is to use the server. the transfer method. The following is a one-to-one Introduction:
1. Using querystring
querystring is a simple value passing method, the disadvantage is that the value to be transferred is displayed in the address bar of the browser, and the object cannot be transferred in this method. If you want to pass a security that is not so important or a simple value, it is best to use this method. The following is a small example to complete value transfer. The procedure is as follows:
1. Create a web form
2. Place a button1 in the new web form, place two textbox1, textbox2
3. Create a click event for the button
Code as follows:
private void button#click
(Object sender, system. eventargs e)
{< br> string URL;
url = "webform2.aspx? Name = "+
textbox1.text +" & Email = "+
textbox2.text;
response. redirect (URL);
}< br> 4. Create a target page named webform2.
5. place two label1, label2
Add the following code to page_load of webform2:
private void page_load
(Object sender, system. eventargs e)
{< br> label1.text = request. querystring ["name"];
label2.text = request. querystring ["email"];
}< br> run the command to view the passed result.
The disadvantage of this method is:
1: In general, this method is usually used to pass the plaintext parameter, that is, the parameter does not need to be kept confidential, and the object cannot be passed when querystring is used to pass the value, the parameter length cannot be greater than 1024 bytes (?), When the parameters have Chinese characters, do you usually need to use the httpulitity. urlencode method to encode and decode the parameters.
Ii. Use session Variables
Using session variables to pass values is the most common method. In this method, values can be transmitted not only to the next page, but also to multiple pages, the variable does not disappear until the value of the session variable is removed. For example:
1. Create a web form
2. Place a button1 in the new web form, and place two textbox1 and textbox2
3. Create a click event for the button
The Code is as follows:
Private void button#click
(Object sender, system. eventargs E)
{
Session ["name"] = textbox1.text; session ["email"] = textbox2.text; response. Redirect ("webform2.aspx ");
}
4. Create a new target page named webform2
5. Place label1 and label2 in webform2.
Add the following code to page_load of webform2:
Private void page_load
(Object sender, system. eventargs E)
{
Label1.text = session ["name"]. tostring ();
Label2.text = session ["email"]. tostring ();
Session. Remove ("name ");
Session. Remove ("email ");
}
Run the command to view the passed result.
The advantage and disadvantage of this method is that the use of session variables often occupies the server's memory usage, so when the webpage traffic is large, the session cannot complete the task well, the session has a timeout, which affects user operations.
Iii. Use server. Transfer
Although this method is a bit complicated, it is also a way to pass values on the page.
For example:
1. Create a web form
2. Place a button1 in the new web form, and place two textbox1 and textbox2
3. Create a click event for the button
The Code is as follows:
Private void button#click
(Object sender, system. eventargs E)
{
Server. Transfer ("webform2.aspx ");
}
4. The textbox1 is returned during the creation process. The value code of the textbox2 control is as follows:
Public string name
{
Get
{
Return textbox1.text;
}
}
Public String email
{
Get
{
Return textbox2.text;
}
}
5. Create a new target page named webform2
6. Place label1 and label2 in webform2.
Add the following code to page_load of webform2:
Private void page_load
(Object sender, system. eventargs E)
{
// Create an instance of the original form
Webform1 WF1;
// Obtain the instantiated handle
WF1 = (webform1) Context. Handler;
Label1.text = wf1.name;
Label2.text = wf1.email;
}
Run the command to view the passed result.
This method has never been used and cannot be evaluated.
4. Other methods for passing values
Application:
Because the application and all the objects it stores can be accessed by different threads at the same time, it is best to store the data that is rarely modified together with the application scope. Ideally, the object is initialized in the application_start event and further access to it is read-only.
In the following example, the file is read in application_start (defined in the Global. asax file), and the content is stored in the dataview object in the application state.
Void application_start () {dataset DS = new dataset (); filestream FS = new filestream (server. mappath ("schemadata. XML "), filemode. open, fileaccess. read); streamreader reader = new streamreader (FS); DS. readxml (Reader); FS. close (); dataview view = new dataview (Ds. tables [0]); application ["Source"] = view ;}
In the page_load method, dataview is subsequently retrieved and used to fill the DataGrid object:
Void page_load (Object sender, eventargs e) {dataview source = (dataview) (application ["Source"]); ...... mydatagrid. datasource = source ;...}
The advantage of this solution is that only the first request pays for data retrieval. All subsequent requests use the existing dataview object. Since the data is never modified after initialization, you do not need to set any rules for serialized access.
The application must use variables that are relatively static compared to the entire project, such as database connection variables. For each user, the variables in each session may not be the same. Generally, the value of the application variable is specified at the end of config. You can also specify it in global. ascx.
COOKIE:
The following example shows how to use client cookies to store user preferences that are easy to lose.
Storing cookies on the client is one of the methods for associating requests with sessions in the session Status of ASP. NET. Cookies can also be directly used to maintain data between requests, but the data will be stored on the client and sent to the server along with each request. The browser has a limit on the cookie size. Therefore, the cookie can be accepted only when the cookie size does not exceed 4096 bytes.
When the data is stored on the client, the page_load method in the cookies1.aspx file checks whether the client has sent cookies. If no, create and initialize a new cookie and store it on the client:
Protected void page_load (Object sender, eventargs e) {If (request. cookies ["preferences1"] = NULL) {httpcookie cookie = new httpcookie ("preferences1"); cookie. values. add ("forecolor", "black ");... response. appendcookie (cookie );}}
On the same page, use the getstyle method again to provide the individual values stored in the cookie:
Protected string getstyle (string key) {httpcookie cookie = request. Cookies ["preferences1"]; If (cookie! = NULL) {Switch (key) {Case "forecolor": Return cookie. Values ["forecolor"]; break;...} return "";}
To make the cookie persistent between sessions, you must set the expires attribute on the httpcookie class to a future date. Except for the cookie. expires value assignment, the code on the following custom. ASPX page is the same as that on the previous example:
Protected void submit_click (Object sender, eventargs e) {httpcookie cookie = new httpcookie ("preferences2"); cookie. values. add ("forecolor", forecolor. value );... cookie. expires = datetime. maxvalue; // never expires response. appendcookie (cookie); response. redirect (State ["Referer"]. tostring ());}
.
Cookie is an obvious advantage and disadvantage when a request is submitted and the data is stored. His shortcomings are described above, such as limited size and inability to save objects. In addition, as the storage time, that is, the Data Validity period, it is indeed the best to save. You can set the cookie expiration time and other attributes. Cookie has many common attributes, including domain and path, which can be obtained on Quickstart.
Viewstate:
ASP. NET provides server-side notes on view status for each control. Controls can use the viewstate attribute on an instance of the statebag class to save its internal state between requests. The statebag class provides dictionary styles to store objects associated with string keys.
The pagestate1.aspx file displays a visible panel and uses the key panelindex to store its indexes in the view State of the page:
Protected void next_click (Object sender, eventargs e) {string prevpanelid = "Panel" + viewstate ["panelindex"]. tostring (); viewstate ["panelindex"] = (INT) viewstate ["panelindex"] + 1; string panelid = "Panel" + viewstate ["panelindex"]. tostring ();...}
Note: If you open this page in multiple browser windows, this name panel is initially displayed in each browser window. Each window can be located independently between panels.
Summary
1. Use application state variables to store data that is rarely modified but frequently used.
2. Use session state variables to store data specific to a session or user. All data is stored on the server. This method is suitable for short-term, massive, or sensitive data.
3. Store a small amount of data that is prone to loss in non-persistent cookies. The data is stored on the client, and is sent to the server upon each request, and becomes invalid when the client ends execution.
4. Store a small amount of non-loss data in persistent cookies. The data is stored on the client until it becomes invalid and is sent to the server upon each request.
5. Store a small amount of requested data in the view State. Data is sent from the server to the client and returned.