Asp. NET built-in objects two

Source: Internet
Author: User
Tags urlencode

(1) Respose object

Output text information using the Response object:

protected void Page_Load (object sender, EventArgs e)
{String message = "Hello, welcome to this website!"  "; Response.Write (message);}

  

Use Response object to implement Web page jump:

protected void Page_Load (object sender, EventArgs e) {    Response.Redirect ("http://www.easou.com");}

  

Use the Response object to output a string like a browser:

protected void Page_Load (object sender, EventArgs e) {    Response.Write (@ "C:\Users\light\Desktop\Sample\Sample\ Default.aspx ");}

To stop the output with the response object:

protected void Page_Load (object sender, EventArgs e) {for    (int ss=1;ss<30;ss++)    {        response.writer (i);        if (i==8)            response.end ();}    }    

To pass parameters using the Response object:

Response.resirect ("Page.aspx? Num=4 ");

(2) Request object

The use of QueryString. Use QueryString to get the string parameters passed from the previous page.

In the Default.aspx:

<div>
<a href= "Page1.aspx? Num=1&name=liu "> Page jump </a></div>

    

In the Page1.aspx.cs:

protected void Page_Load (object sender, EventArgs e) {    Response.Write ("Passed variable Value:");    Response.Write ("num value:" + request.querystring["num"] + "Name value" + request.querystring["name"]); }

  

The value of form, cookie, severvaiables can also be obtained in a similar way. The call method is: request.collection["variable"] (variable is the keyword to query). Collection includes four sets of QueryString, Form, Cookies, Severvaiables. The use can also be request["variable"), the same effect as request.collection["variable". Omitting the collection,request object will be searched in the order of querystring,form,cookies,severvaiables, until the keyword variable is found and its value is returned, otherwise the method returns a null value.

Form collection:

request.form["Name"]. ToString ();

ServerVariable Collection:

request.servervariable[parameter type];

Cookies Collection:

Write Data:

Response.cookies[cookie name]. value= data;

Response.cookies[cookie index number]= data;

Read data:

Cookiesvalue=request.cookies[cookie name]. Value;

Cookiesvalue=request.cookies[cookie index number]. Value;

To move an item out of the data:

Response.Cookies.Remove ("cookie name");

To move all data out:

Response.Cookies.Clear ();

Use of saves (save HTTP requests to disk):

protected void Page_Load (object sender, EventArgs e) {    request.saveas ("G:/sample.txt", True);}

(3) Server object

The use of MachineName. Gets the local server computer name.

protected void Page_Load (object sender, EventArgs e) {    string machinename;    MachineName = Server.MachineName.ToString ();    Response.Write (machinename);}

Use of HtmlEncode and HtmlDecode. Output the

protected void Page_Load (object sender, EventArgs e) {    string str1;    STR1 = Server.HTMLEncode ("

Use of UrlEncode and UrlDecode. The UrlEncode method of the server object encodes the string according to the URL rules. The UrlDecode method of the server object decodes the string according to the URL rules. A URL rule is that when string data is passed to the server as a URL, spaces are not allowed in the string, and special characters are not allowed to appear.

protected void Page_Load (object sender, EventArgs e) {    string str2;    STR2 = Server.URLEncode ("http://www.easou.com");    Response.Write (str2+ "<br/>" + "<br/>");    str2 = Server.urldecode (str2);    Response.Write (STR2);}

(4) ViewState object

Use the ViewState object count.

In the Default.aspx:

<div>    <a href= "Page1.aspx? Num=1&name=liu "> Page jump </a>    <asp:button id=" Button1 "runat=" Server "onclick=" Button1_Click "/> </div>

In the Default.aspx.cs:

protected void Button1_Click (object sender, EventArgs e) {    int count;    if (viewstate["count"] = = null)        count = 1;    else        count = (int) viewstate["Count"] + 1;    viewstate["Count"] = count;    Response.Write ("The number of your single-cell buttons is:" + viewstate["Count"]. ToString ());}

ViewState object security mechanism:

1. Hash coding technology. Hash coding technology is known as a powerful coding technique. Its algorithm idea is to let ASP. NET examines all the data in the ViewState, and then encodes the data by hashing the algorithm. The hashing algorithm produces a short piece of data information, the hash code. Then add the code behind the viewstate message.

The functionality of the hash code is actually the default, and if the programmer wishes to have such a feature, there is no need to take additional steps, but sometimes the developer chooses to disable the feature. To prevent different servers from appearing in a Web site system with different keys. In order to disable hash codes, the enableViewStateMac property of the <Pages> element can be in the Web. config file.

<pages enableviewstatemac= "false"/>

2.ViewState encryption. Although the programmer uses the hash code, the viewstate information can still be read by the user, in many cases it is completely acceptable. But if the viewstate contains information that needs to be kept confidential, it needs to use ViewState encryption.

Set up a separate page to use ViewState encryption:

<%page viewstateencryptionmode= "Always"%>

To set up an entire Web site using ViewState encryption:

<pages viewstateencryptionmode= "Always"/>

Use the ViewState object to persist member variables. Rationale: The Page.prerender event occurs when the member variable is saved in ViewState, and the member variable is retrieved when the Page.load event occurs.

In the Default.aspx:

<table> <tr> <td colspan= "2" > <asp:textbox id= "TextBox1" runat= "Server" width= "100px" Backco Lor= "Beige"/> </td> </tr> <tr> <td> <asp:button id= "Button1" runat= "Server" Wi Dth= "50px" text= "Save Information" onclick= "Button1_Click"/> </td> <td> <asp:button id= "Button2" runat= "s Erver "width=" 50px "text=" read Information "onclick=" button2_click "/> </td> </tr></table>

In the Default.aspx.cs:

protected string textboxcontent = "";p rotected void Page_Load (object sender, EventArgs e) {    if (this. IsPostBack)//loopback   {        textboxcontent = viewstate["Textboxcontent"]. ToString ();    }} protected void Page_PreRender (object sender, EventArgs e) {    viewstate["textboxcontent"] = textboxcontent;} protected void Button1_Click (object sender, EventArgs e) {    textboxcontent = this. TextBox1.Text.ToString ();//Store text information this    . TextBox1.Text = "";//clear Information}protected void button2_click (object sender, EventArgs e) {this    . TextBox1.Text = textboxcontent;//Read textboxcontent information}

Information transfer between pages:

1) Cross-page delivery.

In the Default.aspx:

<div>    asp:textbox id= "TextBox1" runat= "Server" width= "100px" backcolor= "Beige"/>    <br/>    <asp:button id= "Button3" runat= "Server" text= "cross-page delivery" postbackurl= "~/page1.aspx"/></div>

In the Default.aspx.cs:

public string fullcontent{    get    {        return this. Title.tostring () + "" + this. TextBox1.Text.ToString ();    }}    

In the Page1.aspx.cs:

protected void Page_Load (object sender, EventArgs e) {    if (page.previouspage! = null)        Response.Write ( Page.PreviousPage.Title.ToString ());    Default Default1=previouspage as default;    if (DEFAULT1! = null)        Response.Write ("<br/>" + DEFAULT1. fullcontent);//Read default property value}

2) Use QueryString

In the Default.aspx:

<div>        <asp:button id= "Button1" runat= "Server" text= "QueryString" onclick= "Button1_Click"/></ Div>

In the Default.aspx.cs:

protected void Button1_Click (object sender, EventArgs e) {    Response.Redirect ("page1.aspx?name=light&age=22") ;}

In the Page1.aspx.cs:

protected void Page_Load (object sender, EventArgs e) {     Response.Write ("The message passed here is:" + "<br>");    Response.Write ("Name:" + request.querystring["name"]. ToString () + "<br>");    Response.Write ("Age:" + request.querystring["age"]. ToString ());}

(5) Cookie Object

The cookie object is valid for 20 minutes by default, and the cookie is cleared for more than 20 minutes.

Write Data:

Response.cookies[cookie name]. value= data;

Response.cookies[cookie index number]= data;

Read data:

Cookiesvalue=request.cookies[cookie name]. Value;

Cookiesvalue=request.cookies[cookie index number]. Value;

To move an item out of the data:

Response.Cookies.Remove ("cookie name");

To move all data out:

Response.Cookies.Clear ();

Create a Cookie instance:

HttpCookie cookie = new HttpCookie ("test");//Create a cookie instance cookie. Values.add ("Name", "Week Week");//Add the information to be stored, using a combination of key/value cookie. Expires = DateTime.Now.AddYears (1); RESPONSE.COOKIES.ADD (cookie);//Add a cookie to the Respose object of the current page

Get cookie information:

HttpCookie cookie2 = request.cookies["Test"];string name1;//declares a variable to store cookie information    if (cookie2! = null)//To determine if the cookie is empty    {            name1 = cookie2. values["Name"];            Response.Write ("<br><br> saved user name:" + name1);    }        

To modify the cookie value:

    int counter = 0;    if (request.cookies["counter"] = = null)    {         counter = 0;    }    else    {        counter = counter + 1;    }    response.cookies["Counter"]. Value = counter. ToString ();    response.cookies["Counter"]. Expires = System.DateTime.Now.AddDays (1);        

Delete a cookie:

            HttpCookie cookie3 = new HttpCookie ("test");            Cookie3. Expires = DateTime.Now.AddYears ( -1);            RESPONSE.COOKIES.ADD (COOKIE3);

Delete all cookies in the current domain:

            HttpCookie cookie4;            int limit = Response.Cookies.Count;            for (int i = 0; i < limit; i++)            {                cookie4= request.cookies[i];                Cookie4. Expires = DateTime.Now.AddYears (-1);//Set Expiration          Response.Cookies.Add (COOKIE4);//Overwrite        } for            (int i = 0; i < Limit i++)//Determine if the cookie is empty  {                cookie4 = request.cookies[i];                Name = Cookie4. values["Name"];                Response.Write ("<br><br> saved user name:" + name);            }                  

(6) Session object

Read data:

Data =session[variable name] or data =session[index number].

Write Data:

session[variable name]= data or session[index number]= data.

To remove an item of data from a Session object:

Session.remove ("named object");

Session.removeat ("named Object Index");

Remove all data from the Session object:

Session.removeall ();

Session.clear ();

Application Examples:

In the Default.aspx:

    <div> <table> <tr> <td colspan= "2" style= "height:80px" > <asp:label id= "Label1" runat= "server"/> </td> </tr> & Lt;tr> <td colspan= "2" > <asp:label id= "Label2" runat= "server" text= "Please select the Learning to view Birth name: "/> </td> </tr> <tr> <td rowspan=" 2 "style                = "width:200px" > <asp:listbox id= "ListBox1" runat= "Server" width= "100px" height= "100px"/> </td> <td style= "width:120px;height:20px" > <asp:button id= "Butt            On1 "runat=" Server "text=" More information: "onclick=" Button1_Click "/> </td> </tr> <tr> <td style= "width:120px;height:100px" > <asp:label id= "Label3" runat=           "Server"/>     </td> </tr> </table> </div> 

In Default.aspx.cs:

        public class Student {public string stuname;            public string stuage;            public string Stuscore;                Public Student (String stuname, String stuage, String stuscore) {stuname = Stuname;                Stuage = Stuage;            Stuscore = Stuscore; }} protected void Page_Load (object sender, EventArgs e) {if (!this.                IsPostBack) {//define Student object Student student1 = new Student ("Lee Meters", "24", "89");                Student Student2 = new Student ("Yulaw", "22", "95");                Student Student3 = new Student ("Wu Ya", "23", "86");                Session Storage studnet Information session["student1"] = student1;                session["Student2"] = Student2;                session["Student3"] = Student3; Binds the data to the listbox this.                ListBox1.Items.Clear (); This. LISTBOX1.ITEMS.ADD (student1.  Stuname);              This. LISTBOX1.ITEMS.ADD (Student2.                Stuname); This. LISTBOX1.ITEMS.ADD (Student3.            Stuname); }//Display session information this.            Label1.Text = "SessionId:" + Session.SessionID.ToString () + "<br>"; This.            Label1.Text + = "Session number:" + Session.Count.ToString () + "<br>"; This.            Label1.Text + = "Session mode:" + Session.Mode.ToString () + "<br>"; This.        Label1.Text + = "Session validity:" + Session.Timeout.ToString (); } protected void button1_click (object sender, EventArgs e) {if (this. Listbox1.selectedindex = =-1) this.            Label1.Text = ""; else {//Get session key value string key = "Student" + (this. Listbox1.selectedindex + 1).                ToString ();                Get Student object Student Student = (Student) Session[key]; Show student Information this. Label3.text + = "Student Name:" + student.          Stuname + "<br>";      This. Label3.text + = "Student Age:" + student.                Stuage + "<br>"; This. Label3.text + = "Student Score:" + student.            Stuscore; }        }

Session store.

1. In the client store. By default, the client uses cookies to store session information. Sometimes in order to prevent the user from disabling cookies causing the program confusion, do not use cookies to store session information.

2. Store on server side. Include stored in-process, stored out-of-process, and stored in SQL Server.

(7) Application Object

Application object Write Data format:

application[variable name]= data;

application[index number]= data.

Application object read data format:

Data =application[variable name];

Data =application[index number].

To delete an item of data from a Application object:

Application.remove ("named object");

Application.removeat ("Index of Named objects");

To remove all the data from the Application object:

Application.removeall ();

Application.clear ();

Locking: Application.Lock (); Unlock: Application.UnLock (); Use must appear in pairs.

Usage examples:

In the Global.asax.cs:

        protected void Application_Start (object sender, EventArgs e)        {            //code to run when the application starts            application["count"] = 0;        }        protected void Session_Start (object sender, EventArgs e)        {            //new session starts when run code            application.lock ();            int count = Convert.ToInt32 (application["Count"]);            application["Count"] = count + 1;            Application.UnLock ();        }

In the Default.aspx.cs:

        protected void Page_Load (object sender, EventArgs e)        {            //Load page for the first time            if (! IsPostBack)            {                string count = application["Count"]. ToString ();                Response.Write ("Number of Visits:" + Count + "Times");            }        }    

Asp. NET built-in objects two

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.