ASP.NET记住登陆用户名的具体实现
程序员文章站
2024-03-02 13:39:46
.aspx文件中复制代码 代码如下: …
…
<asp:textbox id="txtuser_id" runat="server" maxlength="4" width="120px" bordercolor="lightslategray" borderwidth="1px"></asp:textbox>
…
<asp:imagebutton id="btninsert" runat="server" imageurl="~/images/login.gif" onclick="btninsert_click" />
…
<asp:checkbox id="cbxremeberuser" runat="server" text="记住用户名" font-size="small" forecolor="gray"/>
…
protected void page_load(object sender, eventargs e)
{
if (!ispostback)
{
this.txtuser_id.focus();
if (!object.equals(request.cookies["userid"], null))
{
//创建一个cookie对象,实现记住用户名
httpcookie readcookie = request.cookies["userid"];
this.txtuser_id.text = readcookie.value;
}
}
}
private void createcookie()
{
//创建一个cookie对象
httpcookie cookie = new httpcookie("userid");
//判断checkbox控件是否被选中
if (this.cbxremeberuser.checked)
{
//将用户编号存储到创建的cookie对象中
cookie.value = this.txtuser_id.text;
}
//获取创建的cookie对象的过期时间
cookie.expires = datetime.maxvalue;
//将创建的cookie对象添加到内部cookie集合中
response.appendcookie(cookie);
}
.aspx文件中
复制代码 代码如下:
…
<asp:textbox id="txtuser_id" runat="server" maxlength="4" width="120px" bordercolor="lightslategray" borderwidth="1px"></asp:textbox>
…
<asp:imagebutton id="btninsert" runat="server" imageurl="~/images/login.gif" onclick="btninsert_click" />
…
<asp:checkbox id="cbxremeberuser" runat="server" text="记住用户名" font-size="small" forecolor="gray"/>
…
.aspx.cs文件中
复制代码 代码如下:
protected void page_load(object sender, eventargs e)
{
if (!ispostback)
{
this.txtuser_id.focus();
if (!object.equals(request.cookies["userid"], null))
{
//创建一个cookie对象,实现记住用户名
httpcookie readcookie = request.cookies["userid"];
this.txtuser_id.text = readcookie.value;
}
}
}
private void createcookie()
{
//创建一个cookie对象
httpcookie cookie = new httpcookie("userid");
//判断checkbox控件是否被选中
if (this.cbxremeberuser.checked)
{
//将用户编号存储到创建的cookie对象中
cookie.value = this.txtuser_id.text;
}
//获取创建的cookie对象的过期时间
cookie.expires = datetime.maxvalue;
//将创建的cookie对象添加到内部cookie集合中
response.appendcookie(cookie);
}
protected void btninsert_click(object sender, imageclickeventargs e)
{
…
if (object.equals(request.cookies["userid"], null))
{
//调用自定义方法 createcookie()存储用户名
createcookie();
}
else
{
createcookie();
}
…
}