【问题标题】:Redirect page after showing a message using C#使用 C# 显示消息后重定向页面
【发布时间】:2015-02-07 17:54:45
【问题描述】:

我只是想先显示消息,然后将用户重定向到另一个页面。我遇到的问题是它没有首先显示消息,而是以一种正确的方式重定向页面。 这是我的代码

if (some condition == true)
{
    string message = string.Empty;
    message = "Success.  Please check your email.  Thanks.";
    ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);

    Response.Redirect("Login.aspx");    
}

【问题讨论】:

标签: c# asp.net


【解决方案1】:

实现结果的最佳方法是使用 Javascript(客户端)异步执行。

如果你想在服务器端做,这里有一个例子:

protected void btnRedirect_Click(object sender, EventArgs e)
{
    string message = "You will now be redirected to YOUR Page.";
    string url = "http://www.yourpage.com/";
    string script = "window.onload = function(){ alert('";
    script += message;
    script += "');";
    script += "window.location = '";
    script += url;
    script += "'; }";
    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
}

【讨论】:

    【解决方案2】:

    这是因为您的代码从服务器端重定向,甚至在该脚本到达客户端浏览器之前。您应该删除该重定向并修改您的 javascript,以便在显示该消息后在客户端完成重定向。

    编辑:你一定要检查ASP.NET page life cycle

    【讨论】:

      【解决方案3】:

      这里的问题是你在做两件事:

      1. 将脚本添加到发送到显示 JavaScript 警报的浏览器的输出中。
      2. 使用Response.Redirect 触发HTTP 302 redirect

      后者 (2) 意味着 (1) 实际上没有做任何事情。要在此处实现您想要的,您可以使用 RegisterStartupScript 发送一个脚本,例如:

      alert('Message');
      window.location.href = 'login.aspx';
      

      所以你会删除 Response.Redirect 行并使用:

      ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "'); window.location.href = 'login.aspx'", true);
      

      【讨论】:

        【解决方案4】:

        您可以在 C# 中使用计时器。只需给用户足够的时间来阅读消息,然后将您的用户重定向到您想要的页面。

        这个线程有一个很好的使用计时器的例子:how to use Timer in C#

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多