Asp. NET 5 Global Variables! The method of passing values between pages!__.net

Source: Internet
Author: User
Tags volatile server memory
2009-10-28 13:34
One:

1. Using the QueryString variable querystring is a very simple way of passing values, and he can display the value of the transfer in the browser's address bar. You can use this method if you pass one or more values that are not of high security requirements or are simple in structure. However, this method is not available for passing arrays or objects. Here's an example: A.aspx's C # code private void Button1_Click (object sender, System.EventArgs e) {string s_url; S_url = "b.aspx?name= "+ Label1.Text; Response.Redirect (S_url); C # code private void Page_Load (object sender, EventArgs e) {label2.text = request.querystring[' name '] in b.aspx

2. Using the Application object variable application The scope of the object is the entire global, which means it works for all users. Its commonly used methods are lock and unlock. A.aspx C # code private void Button1_Click (object sender, System.EventArgs e) {application["name"] = Label1.Text; Server.Transfer ("b.aspx"); In b.aspx C # code private void Page_Load (object sender, EventArgs e) {string name; Application.Lock (); Name = application["Name"]. ToString (); Application.UnLock (); }

3. Using the session variable presumably this is the most common use of everyone, and its operation is similar to application, the role of the user, so, excessive storage will lead to the exhaustion of server memory resources. A.aspx C # code private void Button1_Click (object sender, System.EventArgs e) {session["name" = Label.text;} b.aspx C # code PR ivate void Page_Load (object sender, EventArgs e) {string name; name = session[' name ']. ToString (); }

4. Use the cookie object variable this is also common use of the method, as with the session, what it is for each user, but there is an essential difference, that is, cookies are stored on the client, and the session is stored on the server side. And the use of cookies should be used in conjunction with the ASP.net built-in object request. A.aspx C # code private void Button1_Click (object sender, System.EventArgs e) {HttpCookie cookie_name = new HttpCookie ("name" ); Cookie_name. Value = Label1.Text; Reponse.appendcookie (Cookie_name); Server.Transfer ("b.aspx"); B.aspx C # code private void Page_Load (object sender, EventArgs e) {string name; name = request.cookie[' name ']. Value.tostring (); }

5. Using the Server.Transfer method, this can be said to be the method used in the development of the surface image object,   It uses the Server.Transfer method to guide the process from the current page to another page, and the new page uses the response stream from the previous page, so this method is completely object-like, concise and effective. A.aspx C # code public string Name {get{return label1.text;}} private void Button1_Click (object sender, System.EventArgs e) {Server.Transfer ("b.aspx");} b.aspx C # code private void Page_Load (object sender, EventArgs e) {a newweb;//instance a form Newweb = (source) Context.Handler; String name; name = Newweb.name; }

the second:

asp.net WEB FORMS provides developers with event-driven development patterns. However, this simple application development model brings us some small problems, for example, in a traditional ASP application, you can easily through the post method to transfer a value or multiple values from one page to another page, the same method in the asp.net to achieve a bit of trouble. Here, we can solve this situation in other ways. Asp. NET provides us with three kinds of ways, one is to transmit the corresponding value by using the QueryString, one kind is to transmit the corresponding value through the session variable, and is realizes through the Server.Transfer method. The following are described separately:


First, the use of QueryString
QueryString is a very simple way of passing values, the disadvantage of which is to display the value to be transferred in the browser's address bar, and in this method can not pass the object. It's best to use this method if you want to pass a security that is not so important or a simple value. Here is a small example to complete the work of the transfer, the following steps:
1. Create a Web Form
2. Place a button1 in the new Web form, placing two Textbox1,textbox2
3. Create Click events for button buttons
The code is as follows:
private void button1_click
(object sender, System.EventArgs e)
{
string URL;
Url= "Webform2.aspx?name=" +
TextBox1.Text + "&email=" +
TextBox2.Text;
Response.Redirect (URL);
}
4, a new target page named WebForm2
5. Place two Label1,label2 in WebForm2
Add the following code to the Page_Load of WebForm2:
private void Page_Load
(object sender, System.EventArgs e)
{
label1.text=request.querystring["Name"];
label2.text=request.querystring["email"];
}
Run, you can see the results after the delivery.

The disadvantage of this approach is:
1: Generally speaking this method usually uses to pass the plaintext parameter, namely does not need the secret parameter, simultaneously when uses the QueryString biography to pass the object, the parameter length cannot be more than 1024 bytes (. , when the parameters are in Chinese, it is usually necessary to use the Httpulitity.urlencode method to encode and reconcile the parameters.


Second, the use of Session variables

The most common way to use the session variable is to pass the value to the next page and cross over to multiple pages until the value of the session variable is removed, and the variable disappears. For example, take a look at:
1. Create a Web Form
2. Place a button1 in the new Web form, placing two Textbox1,textbox2
3. Create Click events for button buttons
The code is as follows:
private void button1_click
(object sender, System.EventArgs e)
{
session["Name"]=textbox1.text;   session["Email"]=textbox2.text; Response.Redirect ("webform2.aspx");
}
4, a new target page named WebForm2
5. Place two Label1,label2 in WebForm2
Add the following code to the 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, you can see the results after the delivery.

The advantages and disadvantages of this method is: the use of session variables will often occupy the server-side memory use, so the web traffic is very large, the session will not be a good completion of the task, due to the session has a timeout, So in the use of the user has a certain effect on the operation.

Iii. Use of Server.Transfer
Although this approach is a bit complicated, it's also a way to pass a value on a page.
For example, take a look at:
1. Create a Web Form
2. Place a button1 in the new Web form, placing two Textbox1,textbox2
3. Create Click events for button buttons
The code is as follows:
private void button1_click
(object sender, System.EventArgs e)
{
Server.Transfer ("webform2.aspx");
}
4, the creation process to return the value of the Textbox1,textbox2 control code is as follows:
public string Name
{
Get
{
return TextBox1.Text;
}
}

public string EMail
{
Get
{
return TextBox2.Text;
}
}
5, a new target page named WebForm2
6. Place two Label1,label2 in WebForm2
Add the following code to the Page_Load of WebForm2:
private void Page_Load
(object sender, System.EventArgs e)
{
Create an instance of the original form
WebForm1 WF1;
Get the instantiated handle
wf1= (WebForm1) Context.Handler;
Label1.text=wf1. Name;
Label2.text=wf1. EMail;

}
Run, you can see the results after the delivery.

This method has not been used and cannot be evaluated.

4, other methods of 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 only infrequently modified data 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 application state in the DataView object.
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 then retrieved and used to populate 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 the cost of retrieving data. All subsequent requests use an existing DataView object. Since data is never modified since it was initialized, there is no need to make any provision for serialization access.

Application have to use variables that are generally relatively static relative to the entire project, such as database connection variables. For each user, each session is not necessarily the same variable is not applicable. Usually the value of the application variable is specified at the config end. can also be specified in Global.ascx.

Cookies:
The following example shows how to use the client Cookie to store volatile user preferences.
Storing cookies on the client is one of the methods that ASP.net session state will request to be associated. Cookies can also be used directly to persist data between requests, but the data is then stored on the client and sent to the server along with each request. The browser has a limit on the size of the Cookie, so only no more than 4096 bytes can be guaranteed to be accepted.
When the data is stored on the client, the Page_Load method in the file cookies1.aspx checks whether the client has sent a Cookie. If not, 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) {Httpcook         IE 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 a Cookie persistent between sessions, you must set the Expires property on the HttpCookie class to a future date. In addition to the Cookie.expires assignment, the following custom. aspx page has the same code as the previous example:
protected void Submit_click (Object sender, EventArgs e) {HttpCookie cookie = new HttpCookie ("Preferences2"); Cookie.     Values.add ("ForeColor", Forecolor.value); ... cookies. Expires = DateTime.MaxValue;     Never Expires Response.appendcookie (cookie); Response.Redirect (state["Referer"). ToString ());}

Cookies are an obvious advantage and disadvantage as a way of submitting, storing data in a request. His shortcomings are described above, such as limited size, can not save objects, and, in addition, as the preservation of time, that is, the validity of the data, is indeed the best preserved. We can set the cookie by setting the expiration time and so on. Cookies have many common properties, including Domain,path, which can be obtained on QuickStart.
ViewState:
asp.net a server-side note that provides view state for each control. Control can use the ViewState property on an instance of a class StateBag to save its internal state between requests. The StateBag class provides dictionary-style interfaces to store objects associated with string keys.
The file pagestate1.aspx displays a visible panel and uses the key panelindex to store its index in 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 that if you open the page in more than one browser window, the name panel will initially appear in each browser window. Each window can be positioned independently from one panel to another.
Summary
1. Use application state variables to store data that is rarely modified but often used.
2. Use session-state variables to store data specific to a session or user. The data is all stored on the server. This method is suitable for short-term, large or sensitive data.
3. Store a small amount of volatile data in a non-persistent Cookie. The data is stored on the client, sent to the server on each request, and invalidated at the end of the client's execution.
4. Storing a small amount of non-volatile data in a persistent Cookie. The data is stored on the client until it is invalidated and sent to the server on each request.
5. Store a small amount of request-specific data in view state. Data is sent from the server to the client and returned.

======================== Supplement ===================================

Setting and Reading methods for C # global variables

Method One: Web.config file
--Settings:
Adding the keyword key to the web.config file is done through the <appSettings> tag, but the appSettings tag is usually placed in <system.web>.....</system.web > tag outside. Cases:
<configration>
<appSettings>
<add key= "connString1" value= "Server=localhost;user id=sa;pwd=;d atabase= database name"/>
<add key= "connString2" value= "Provider=Microsoft.Jet.OLEDB.4.0;Data source= database Path"/>
</appSettings>
<system.web>
</system.web>
</configration>

--read:
To reference these database connection strings in code, You need to add a reference to the System.Configuration namespace that contains the ConfigurationSettings class in the namespace, and its static method ConfigurationSettings.AppSettings property to get the web.config text The set of <appSettings> section in the piece, the Read value is string type. For example:

Using System.Configuration;
String conn1 = configurationsettings.appsettings["ConnString1"];
String conn2 = configurationsettings.appsettings["ConnString2"];
SqlConnection myConn1 = new SqlConnection (CONN1);
OleDbConnection myConn2 = new OleDbConnection (CONN2);

In VS2005, configurationsettings.appsettings can be replaced by configurationmanager.appsettings.

Method Two: Gloab file
--Settings:
Adding in the global file
protected void Session_Start (Object sender, EventArgs e)
{
session["sqlconnectionstring"] = "uid=username;pwd=password;database=mytest;server=localhost; Connect timeout=300 ";
}

--read:
Application in code:
String strconnection=session["sqlConnectionString"]. ToString ();
Sqlconnection_1=new SqlConnection (strconnection);

It is recommended to use the first method. More flexible

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.