I have a working login form. I was just trying to do a simple test to see if it worked and it seems to only work when posting back a second time. In other words…
I enter my username/password and push login button, it posts back but doesn’t show i’m logged in.
Upon clicking the button again, reloading, etc. it will postback again with the desired result.
// from my pageload
//System.Threading.Thread.Sleep(new TimeSpan(0, 0, 0, 10));
//didn't work
if (PageBase.Account.AuthenticatedUser != null) //if user is logged in...
formLogin.Attributes.Add("Style", "background-color:Green");
else
formLogin.Attributes.Add("Style", "background-color:Red");
// just changed the background color. 2nd postback it turns green.
Thanks for your help and input.
EDIT: More code as requested.
public class AccountManager {
public Website.User AuthenticatedUser {
get {
int id = Convert.ToInt32(( (object)HttpContext.Current.Session["user_id"] ??
(object)(HttpContext.Current.Request.Cookies["USER_ID"] ??
new HttpCookie("bugfixcookie") { Value = "0"}).Value));
var user = (from u in new MyWebsiteEntities().Users where u.ID == id select u).FirstOrDefault();
return user;
}
}
// create user,
public bool Login(string username, string password, bool remember) {
var result = (from u in new MyWebsiteEntities().Users
where username == u.Username && password == u.Password select u).FirstOrDefault();
if (result != null) {
if (remember) HttpContext.Current.Response.Cookies.Add(new HttpCookie("USER_ID", result.ID.ToString()));
HttpContext.Current.Session["user_id"] = result.ID.ToString();
return true;
} else return false;
}
public void Logout() {
HttpContext.Current.Response.Cookies.Remove("USER_ID");
HttpContext.Current.Session.Remove("user_id");
}
}
And…
public class PageBase : System.Web.UI.Page
{
public static AccountManager Account { get { return new AccountManager(); } }
}
Front End
<form runat="server" id="formLogin">
<asp:TextBox runat="server" ID="textKey" style="display:none" />
<asp:CheckBox runat="server" ID="checkboxRemember" />
<div>
<span id="un">Username</span><br />
<asp:TextBox runat="server" ID="textUsername" />
</div>
<div>
<span id="pw">Password</span><br />
<asp:TextBox runat="server" ID="textPassword" TextMode="Password" />
</div>
<asp:Button runat="server" ID="buttonLogin" OnClick="buttonLogin_click" />
<asp:Button runat="server" ID="buttonRegister" OnClick="buttonRegister_click" />
</form>
Thanks again!
Suggest moving the Page Load Code above to Page_PreRender Event. Reason being that Page Load runs first then Button Events then PreRender. So Page Load populates Variables and Preps the code for work, then the Button event occurs and the Page does work, then when all work is done Pre Render can collect up changed and unchanged information needed to update the page just before it is sent to the browser. This flow would allow the login button to be pressed, login to occur and then the page come back properly formatted. Hope this Helps