Hi Guys,
I'm trying to create a simple webpage which has a login form. When the user successfully logs in, I want a cookie to be stored with the name "MyCookie", and a value of "1". Then I want the login form to hide and instead display a textbox with the value just set (1).
I've got it saving the cookie, but when you refresh the page, it goes back to the log in form.
My Code:
Index.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="_Default" %>
<%@ Register src="SmallLogInArea.ascx" tagname="SmallLogInArea" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome</title>
<link href="styles.css" rel="stylesheet" type="text/css" /></head>
<body>
<uc1:SmallLogInArea ID="SmallLogInArea1" runat="server" />
</body>
</html>
SmallLogInArea.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SmallLogInArea.ascx.cs" Inherits="SmallLogInArea" %>
<link href="styles.css" rel="stylesheet" type="text/css" />
<asp:MultiView ID="HeaderLogInBox" runat="server">
<asp:View ID="Login" runat="server">
<div id="headerLogin">
<fieldset class="hiddenFieldset">
<span class="login_text">USERNAME</span>
<asp:TextBox ID="login_un" runat="server" CssClass="login_textbox"></asp:TextBox>
<br />
<span class="login_text">PASSWORD</span>
<asp:TextBox ID="login_pw" runat="server" TextMode="Password"
CssClass="login_textbox"></asp:TextBox>
<br />
<asp:Button ID="login_submit" runat="server" Text="LOG IN"
CssClass="login_submit" onclick="login_submit_Click" />
</fieldset>
</div>
</asp:View>
<asp:View ID="LoggedIn" runat="server">
<div id="headerLoggedin">
<asp:TextBox ID="myCookieValue" runat="server" Text="0"></asp:TextBox >
</div>
</asp:View>
</asp:MultiView>
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie userCookie = Request.Cookies["MyCookie"];
if (userCookie == null) //////when you refresh after a successfull log in, userCooki is null - why?
HeaderLogInBox.ActiveViewIndex = 0; //Show the login box
else
{
HeaderLogInBox.ActiveViewIndex = 1; //Show the welcome box
this.myCookieValue.Text = userCookie["myValue"];
}
}
protected void login_submit_Click(object sender, EventArgs e)
{
if (Authenticated(username, password))
{
HttpCookie userCookie = Request.Cookies["MyCookie"];
if (userCookie == null)
{
userCookie = new HttpCookie("MyCookie");
}
userCookie["myValue"] = "1";
userCookie.Expires = DateTime.Now.AddMinutes(15);
Response.Cookies.Add(userCookie);
HeaderLogInBox.ActiveViewIndex = 1;
this.myCookieValue.Text = userCookie["myValue"]
}
}
I can see that the cookie is being created, but when I refresh the page, it doesnt pick up that the cookie is there & shows the login form instead :/
Any ideas where I'm going wrong?
Thanks,
Michael