在 ASP.NET 中使用不同的重定向参数重定向到同一页面

Redirecting to the same page with different redirect parameters in ASP.NET

我制作的这个页面基本上接受了用户对日期的请求,并将在该日期进行一些 select 查询(但是数据库部分并不重要)。有一个文本框 (txtDate) 和一个按钮 (setDate) 用于将 txtDate 中的字符串作为 URL 中的日期参数重定向到同一页面。在 PageLoad 上,我想获取当前的 QueryString[Date] 并将其放回 txtDate(以便用户可以看到 selected 的日期),但是,每当我设置该文本框时,它都会自动请求旧的 QueryString到我要的新的。搞不懂。

这是Page_Load:

    String dateInput = null;
    dateInput = Request.QueryString["Date"];
    txtDate.Text = dateInput.Replace("-", "/"); //if I just comment this out, it works perfectly fine

这是点击按钮:

    String s = null;
    s = txtDate.Text.Replace("/", "-");
    if (s == "") //if empty sends the current date
    {
        Response.Redirect("Default.aspx?Date=" + DateTime.Today.ToString("MM-dd-yyyy"));
    }
    else //sends the users date
    {
        Response.Redirect("Default.aspx?Date=" + HttpUtility.UrlEncode(s));
    }

我不知道我是否解释得很好,但它是这样工作的:

当前日期参数中的 3/14/2016

在 txtDate 中输入新日期:03/16/2016 并点击 setDate 按钮

当且仅当我将 txtDate.Text 设置为当前参数 (03/16/2016) 时重定向回 3/14/2016,否则它会正确重定向到新的 Date 参数

我已经有很长时间没有尝试 WebForms 了,但如果我是对的,您需要在更新文本框之前检查它是否是回发。

所以基本上只是包装你的

txtDate.Text = dateInput.Replace("-", "/"); //if I just comment this out, it works perfectly fine

if (!Request.IsPostback)
{
    txtDate.Text = dateInput.Replace("-", "/"); //if I just comment this out, it works perfectly fine
}

总结一下...这里发生的只是您的 Page_load 事件触发了两次。第一次游览 button_click 活动,然后第二次游览您的重定向。单击按钮时,您将获取查询参数并将其设置为您的文本框,然后再更改查询字符串。这就是为什么如果您删除该行,一切都会正常工作的原因。您需要做的就是检查它是否是回发。