Asp.net session and cookie value passing Method

Source: Internet
Author: User

Session: in the memory of the server;

COOKIE: in the browser of the client;

 

Generally, when session is used, there will be an entity class used to store user name and other data, so here we define a class;

There are two fields: user name and password;

 

Public class usertest
{
Public String username {Get; set ;}
Public String userpwd {Get; set ;}
}

 

Then we need to obtain the source of the stored data.

 

String username = this.txt loginid. Text. Trim ();
String userpwd = this.txt loginpwd. Text. Trim ();

 

Then, the data is put into the session.

 

Usertest user = new usertest ();
User. Username = username;
User. userpwd = userpwd;
Session ["username"] = user;

 

Now we have saved it. How can we get it? Add the following code when loading the page!

 

If (! Ispostback)
{
If (session ["username"]! = NULL)
{
Usertest user = session ["username"] As usertest;
Response. Write ("<SCRIPT> alert ('Welcome" + User. username + "'); </SCRIPT> ");}
}

 

The above is the session usage;

 

The following describes how to use cookies. The httpcookie class is required;

Storage value:

String loginid = this.txt login. Text. Trim ();
Httpcookie cookie = new httpcookie ("username", loginid );
Response. Cookies. Add (cookie );

 

In this way, the data is stored in the cookie. Of course, this is only the storage method of Asp.net. You can also use the jquery cookie to store the data.

 

Valid value:

 

If (! Ispostback)
{
If (request. Cookies ["username"]! = NULL)
{
This.txt login. Text = request. Cookies ["username"]. value;
}

}

 

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.