在额外的回发之前,回发不会显示更改?

时间:2011-11-23 18:56:51

标签: c# asp.net postback pageload

我有一个有效的登录表单。我只是想做一个简单的测试,看它是否有效,它似乎只在第二次回复时才有用。换句话说......

我输入我的用户名/密码并按下登录按钮,它会回发但不会显示我已登录。

再次点击按钮,重新加载等,它将再次回传所需的结果。

// 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.

感谢您的帮助和意见。

编辑:根据要求提供更多代码。

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");
    }
}

和...

public class PageBase : System.Web.UI.Page
{
    public static AccountManager Account { get { return new AccountManager(); } }
}

前端

<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>

再次感谢!

1 个答案:

答案 0 :(得分:4)

建议将上面的页面加载代码移动到Page_PreRender事件。原因是页面加载首先运行,然后按钮事件然后运行PreRender。因此,页面加载填充变量并准备工作代码,然后发生Button事件并且页面确实起作用,然后当所有工作完成时,预渲染可以收集在页面发送到页面之前更新页面所需的已更改和未更改的信息。浏览器。此流程将允许按下登录按钮,登录发生,然后页面返回正确格式化。希望这有助于