Asp.net的Session和Cookie传值方式
Session:在服务器的内存中;
Cookie:在客户端的浏览器中;
一般在使用Session的时候,都会有一个实体类,用于存储用户名等数据,所以在这里我们定义一个类;
里面就放两个字段:用户名,和密码;
public class UserTest
{
public string UserName { get; set; }
public string UserPwd { get; set; }
}
{
public string UserName { get; set; }
public string UserPwd { get; set; }
}
然后我们要获取存数据来源
string userName = this.txtLoginId.Text.Trim();
string userPwd = this.txtLoginPwd.Text.Trim();
string userPwd = this.txtLoginPwd.Text.Trim();
接着就是把数据放到Session中了。
UserTest user = new UserTest();
user.UserName = userName;
user.UserPwd = userPwd;
Session["UserName"] = user;
user.UserName = userName;
user.UserPwd = userPwd;
Session["UserName"] = user;
现在我们存是存好了,那我们该怎么取呢?在页面加载的时候加上如下代码!
if (!IsPostBack)
{
if (Session["UserName"] != null)
{
UserTest user = Session["UserName"] as UserTest;
Response.Write("<script>alert('欢迎您"+user.UserName+"会员');</script>");
{
if (Session["UserName"] != null)
{
UserTest user = Session["UserName"] as UserTest;
Response.Write("<script>alert('欢迎您"+user.UserName+"会员');</script>");
}
}
}
以上就是Session的用法;
下面说一下Cookie的用法;需要用到HttpCookie类;
存值:
string LoginId = this.txtLogin.Text.Trim();
HttpCookie cookie = new HttpCookie("UserName", LoginId);
Response.Cookies.Add(cookie);
HttpCookie cookie = new HttpCookie("UserName", LoginId);
Response.Cookies.Add(cookie);
这样就将数据存放到Cookie中了,当然这只是Asp.net的存放方式,你也可以使用JQuery的Cookie存放。
取值:
if (!IsPostBack)
{
if (Request.Cookies["UserName"] != null)
{
this.txtLogin.Text = Request.Cookies["UserName"].Value;
}
}
{
if (Request.Cookies["UserName"] != null)
{
this.txtLogin.Text = Request.Cookies["UserName"].Value;
}
}