繁体   English   中英

使用C#显示消息后重定向页面

[英]Redirect page after showing a message using C#

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

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

实现结果的最好方法是与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);
}

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

编辑:您绝对应该检查ASP.NET页面生命周期

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

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

后者(2)表示(1)实际上不做任何事情。 为了在这里实现您想要的,您可以使用RegisterStartupScript向下发送一个脚本,如下所示:

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

因此,您将删除 Response.Redirect行并使用:

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

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

该线程有一个使用计时器的好例子: 如何在C#中使用Timer

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM