C # development and learning methods for passing values between pages and built-in objects in --.net C,

Source: Internet
Author: User
Tags html header
1.QueryString is a very simple way to pass values. He can display the transmitted value in the browser's address bar. This method can be used when passing one or more values with low security requirements or simple structure. But for passing arrays or objects, this method cannot be used. Below is an example:
 
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 in b.aspx
private void Page_Load (object sender, EventArgs e)
 {
Label2.Text = Request.QueryString ["name"];
}
 
The query value is classified into post, and the get format is as follows:
// post request
string name = Request ["name"]. toString ();
string name = Request.Form.Get ("name"). toString ();
// get request
string name = Request.QueryString ["name"]. toString ();
 


But I found that both post and get pass values are available

string name = Request ["name"]. toString ();

 


The differences between the get and post methods in form submission are summarized as follows:

1. get is to get data from the server, and post is to send data to the server.

2. get is to add the parameter data queue to the URL pointed to by the ACTION attribute of the submitted form, and the value corresponds to each field in the form one by one, you can see in the URL. Post is an HTTP post mechanism that places each field in the form and its content in the HTML HEADER and transmits it to the URL pointed to by the ACTION attribute. The user does not see this process.

3. For the get method, the server uses Request.QueryString to get the value of the variable. For the post method, the server uses Request.Form to get the submitted data.

4. The amount of data transmitted by get is small and cannot be larger than 2KB. The amount of data transmitted by the post is large, and is generally defaulted to unlimited. But in theory, the maximum amount is 80KB in IIS4 and 100KB in IIS5.

5. Get security is very low, post security is high.




2. Using Application object variables
The scope of the Application object is the entire global, which means that it is valid for all users. Its commonly used methods are Lock and UnLock.
C # code for a.aspx
 private void Button1_Click (object sender, System.EventArgs e)
 {
Application ["name"] = Label1.Text; Server.Transfer ("b.aspx");
}
C # code in b.aspx
private void Page_Load (object sender, EventArgs e)
{
string name;
Application.Lock ();
name = Application ["name"]. ToString ();
Application.UnLock ();
}
 
3. Using Session Variables
Presumably this is definitely the most common usage in everyone's use. Its operation is similar to Application and acts on the individual user. Therefore, excessive storage will lead to exhaustion of server memory resources.
C # code for a.aspx
 private void Button1_Click (object sender, System.EventArgs e)
 {
Session ["name"] = Label.Text;
}
C # code in b.aspx
private void Page_Load (object sender, EventArgs e) {
string name;
name = Session ["name"]. ToString ();
}
 
4. Using Cookie Object Variables
This method is also commonly used by everyone. Like Session, it is for every user, but there is an essential difference, that is, the cookie is stored on the client, and the session is stored on the server. And the use of cookies should be used in conjunction with the ASP.NET built-in object Request.
C # code for a.aspx
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");
}
 C # code in b.aspx
private void Page_Load (object sender, EventArgs e)
 {
 string name; name = Request.Cookie ["name"]. Value.ToString ();
}
5. Use the Server.Transfer method
This can be said to be the method used in the development of the face object. It uses the Server.Transfer method to direct the process from the current page to another page. The new page uses the response flow of the previous page, so this method is a complete face. Object-oriented, concise and effective.
 
C # code for a.aspx
public string Name {
 get {return Label1.Text;}
 }
 private void Button1_Click (object sender, System.EventArgs e) {
 Server.Transfer ("b.aspx");
}
C # code in b.aspx
private void Page_Load (object sender, EventArgs e) {
a newWeb; // Instance a form
newWeb = (source) Context.Handler;
string name; name = newWeb.Name;
 }
 
The following describes the disadvantages and advantages of value passing
cookie
     Method: Classic method of storing data on the client.
     Disadvantages: low security, limited by client settings, only 20 cookies are stored on one site, each with a capacity of 4096 bytes
Session
     Method: Store user data on the server.
     Features: Asp.net can set session storage mode, location, and whether the storage of SessionID depends on cookies.
             Objects can be stored directly.
     Disadvantages: hidden dangers of failure in asp.net
Cache
     Method: Store user data in the server-side data cache.
     Features: Can greatly improve efficiency. Objects can be stored directly.
Appliction
     Method: The data is stored here, which is equivalent to a global variable.
     Features: Can store objects directly. Shared data across the site
ViewState
     Method: Asp.net's unique mechanism is used to restore the state of the page.
     Features: Serialize each control of the page and its stored data in a hidden domain named _ViewState.
     Disadvantages: Exist in HTML, low security. You can set encryption and authentication, but the amount of data will increase greatly and the efficiency will be affected.
Static
     Method: Store the data in a static variable.
     Features: Conducive to improve efficiency.
     Disadvantages: If it is not used properly, it will cause data disorder between users or pages, causing great hidden dangers. It is recommended to assign the value only once, and it is absolutely forbidden to change this value for a single user.
 
 
 

ASP.NET built-in objects include 1.Response 2.Request 3.Server 4.Application 5.Session 6.Cookie

1 The Request object is mainly for the server to obtain some data from the client browser, including parameters passed from the HTML form using the Post or GET method, cookies, and user authentication.

2 The Request object is a member of the Page object.

3 The program can be used directly without making any declarations; its class name is HttpRequest with many properties, but there are few methods, only one BinaryRead ()

1. Get data using Request.Form property

  Through this property, read the form data between.

Note: The submission method should be set to "Post". Compared with the Get method, using the Post method can send a large amount of data to the server

2. Use Request.QueryString property to get data

  The QuerySting property of the Request object can get a collection of HTTP query string variables. Through this property, we can read the address information http: //localhost/aaa.aspx? Uid = tom & pwd = abc where the data marked in red. Note: The submission method should be set to "Get"

3. Problem: Request.Form is used when the form submission method is Post, while Request.QueryString is used when the form submission method is Get. If it is used incorrectly, no data can be obtained.

Solution: Use Request ("element name") to simplify operations.

 
Response object: send data from the server to the browser


     1. <% =…%> Response.Write ("alert ('Welcome to learn ASP.NET')")

Response.Write ("")


2. The Redirect method of the Response object redirects the client browser to another URL, that is, jumps to another web page. For example: Response.Redirect ("http://www.example.com/")

3. Response.End () terminates the current page



4.Response.WriteFile (FileName) where: FileName refers to the file name of the file to be output to the browser



The Server object provides access to methods and properties on the server. Its class name is HttpServerUtility.

The main properties of the Server object are

MachineName: Get the computer name of the server.

ScriptTimeout: Get and set the request timeout (in seconds).

 

Method name Description

CreateObject creates a server instance of a COM object.

Execute execute another aspx page on the current server, return to this page to continue execution after executing this page

HtmlEncode HTML encodes the string to be displayed in the browser and returns the encoded string.

HtmlDecode decodes an HTML-encoded string and returns the decoded string.

PathMapPath returns the physical file path corresponding to the specified virtual path on the web server.

Transfer terminates execution of the current page and starts execution of a new page for the current request.

RlUrlEncode encodes a string representing a URL for reliable HTTP transmission from a web server to a client through a URL.

UrlDecode decodes the encoded URL string and returns the decoded string.

UrlPathEncode URL-encodes the path portion of a URL string and returns the encoded string.

Encoding: Server.HtmlEncode ("HTML code")

Decoding: Server.HtmlDecode ("Encoded HTML")

1. The MapPath method of the Server object converts a virtual path or a relative path relative to the current page to a physical file path on the Web server.

grammar:

Server.MapPath ("virtual path")

String FilePath

FilePath = Server.MapPath ("/")

Response.Write (FilePath)

 

 


The purpose of the Application object in actual network development is to record information about the entire network, such as the number of people online, online lists, opinion surveys, and online elections. Share information among multiple users of a given application and persist the data while the server is running. And the Application object also has methods to control access to application-level data and events that can be used to trigger processes when the application starts and stops.



 

1. Use Application object to save information Application ("key name") = value or Application ("key name", value)

     Get Application object information variable name = Application ("key name")

     Or: variable name = Application.Item ("key name")

     Or: Variable name = Application.Get ("key name") Update the value of the Application object

Application.Set ("key name", value)

Delete a key

Application.Remove ("key name", value)

Delete all keys

Application.RemoveAll () or Application.Clear ()

  2. There may be situations where multiple users access the same Application object at the same time. In this way, multiple users may modify the same Application named object, causing data inconsistencies. The HttpApplicationState class provides two methods, Lock and Unlock, to solve the problem of synchronization of access to the Application object, allowing only one thread to access the application state variables at a time.

About lock and unlock

Lock: Application.Lock ()

Access: Application ("key name") = value

Unlock: Application.Unlock ()

Note: The Lock and UnLock methods should be used in pairs. Can be used for website visitors, chat rooms and other devices.

3. Use the Application event

A special optional file can be included in an ASP.NET application-the Global.asax file, also known as an ASP.NET application file, which contains information for responding to application-level events raised by ASP.NET or HTTP modules Code. The Global.asax file provides 7 events, 5 of which apply to the Application object

Event name Description

Application_Start fires when the application starts

Application_BeginRequest fired at the beginning of each request

Application_AuthenticateRequest Fired when trying to authenticate the user

Application_Error is raised when an error occurs

Application_End fires at the end of the application

 

 
Session is a session, which refers to a user's visit to a site within a period of time.



The Session object corresponds to the HttpSessionState class in .NET and represents "session state". It can store information related to the current user session.

The Session object is used to store the information required by a specific user session from when a user starts to access a specific aspx page until the user leaves. When the user switches pages in the application, the variables of the Session object are not cleared. For a web application, the content of the Application object accessed by all users is exactly the same; the content of the Session object accessed by different user sessions is different. Session can save variables, which can only be used by one user, that is, each web browser has its own Session object variable, that is, the Session object is unique.

(1) Add new items to the session state

 The syntax format is:

Session ("key name") = value

Or

Session.Add ("key name", value)

(2) Get the value in session state by name

The syntax format is:

Variable = Session ("key name")

Or

Variable = Session.Item ("key name")

(3) Delete items in the session state set

The syntax is: Session.Remove ("key name")

(4) Clear all values in the session state

The syntax is: Session.RemoveAll ()

Or Session.Clear ()

(5) Cancel the current session

The syntax is: Session.Abandon ()

(6) Set the timeout period of the session state, in minutes.

The syntax is: Session.TimeOut = value

Global.asax file has 2 events applied to the Session object

Event name Description

Session_Start fires when the session starts

Session_End fires at the end of the session

 

 

A cookie is a piece of text that a web server stores on a user's hard disk. Cookies allow a Web site to save information on a user's computer and retrieve it later. The pieces of information are stored in the form of 'key / value' pairs.

Cookie is a text file stored on the client's hard disk. It can store information about a specific client, session or application. It corresponds to the HttpCookie class in .NET.

There are two types of cookies: session cookies (session cookies) and persistent cookies.

The former is temporary and will cease to exist once the session state has ended;

The latter has a definite expiration date, before which the cookies are stored as text files on the user's computer. The cookie created on the server and output to the client can be implemented using the Response object.

 


HttpCookie cookie = Request.Cookie ["user"]; // Create a cookie object

cookie.Expires = DateTime.MaxValue; // Set the expiration time

cookie.Values.Add ("Iaddress", a); // Add cookie value

Response.AppendCookie (cookie); // Add the cookie to the server accordingly

response.cookies [""]. Values = data; // write data, write server-side data to client

string c = request. cookie.Values ["address"]; // Read data

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.