表格自我提交

时间:2012-05-22 17:14:37

标签: c# asp.net html post pageload

所以我试图让一个页面提交给自己,然后在出错时或其他地方成功重定向到自己。

我有在VB.NET中运行的示例代码,但我正在尝试使用相同的代码在C#中工作。我觉得错误在于使用Page_Load - 我觉得我应该使用另一个电话。

由于代码现在,我得到一个无限重定向循环,这是不可接受的。

以下是代码:

<% @Page Language="C#" Debug="true" %>
<% @Import Namespace="System.Web" %>
<script language="C#" runat="server">
    void Page_Load(object sender,EventArgs e) {
        if( Request.Form["username"] == "admin" && Request.Form["password"] ==  "password") {
            HttpContext.Current.Session["username"] = Request.Form["username"];
            HttpContext.Current.Session["password"] = Request.Form["password"];
            Response.Redirect("elsewhere.html");
        }
        else {
            Response.Redirect("login.aspx?errors=1");
        }
    }
</script>

<!-- #include file="header.html" -->

<form action="" method="post">
    <div id="errors">Incorrect Username or Password</div>
    <div><span>Username:</span><input name="username" /></div>
    <div><span>Password:</span><input name="password" type="password" /></div>
    <div><input type="button" value="Login" id="loginbutton" /></div>
</form>

<!-- #include file="footer.html" -->

谢谢!

2 个答案:

答案 0 :(得分:2)

我认为你错过了

if (IsPostBack) {
   //Your code here
}

这将允许您的代码仅在表单刚刚提交时才会触发。

答案 1 :(得分:1)

无限重定向的原因是

 Response.Redirect("login.aspx?errors=1");

当第一次加载页面时,Request.Form [“username”] ==“admin”,这些条件中的任何一个都会导致else部分执行。它无限地一次又一次地加载login.aspx。

当页面回发时,我们将这些语句执行。你的代码就是。

if(Page.IsPostBack)
{
    if( Request.Form["username"] == "admin" && Request.Form["password"] ==  "password") {
                HttpContext.Current.Session["username"] = Request.Form["username"];
                HttpContext.Current.Session["password"] = Request.Form["password"];
                Response.Redirect("elsewhere.html");
            }
            else {

                    Response.Redirect("login.aspx?errors=1");
            }
}
相关问题