简体   繁体   English

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

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

I am simply trying to show message first then redirect the user to another page. 我只是尝试先显示消息,然后将用户重定向到另一个页面。 The issue i am having is that it is not showing the message first but it is redirecting the page right a way. 我遇到的问题是它没有首先显示该消息,而是以某种方式重定向了页面。 Here is my code 这是我的代码

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

The best way to achieve your result is doing it asynchronously with Javascript (client-side). 实现结果的最好方法是与Javascript(客户端)异步进行。

If you want do it server-side, here is an example: 如果要在服务器端执行此操作,请参考以下示例:

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

That is because your code redirects from server-side, even before that script reaches the client browser. 那是因为您的代码从服务器端重定向,甚至在该脚本到达客户端浏览器之前也是如此。 You should remove that redirect and modify your javascript so that the redirect is done at the client side AFTER that message is displayed. 您应该删除该重定向并修改JavaScript,以便在显示该消息后在客户端完成重定向。

EDIT: You should definitely check on ASP.NET page life cycle . 编辑:您绝对应该检查ASP.NET页面生命周期

The issue here is that you're doing two things: 这里的问题是您正在做两件事:

  1. Adding a script to the output that is sent to the browser that presents a JavaScript alert. 将脚本添加到发送到浏览器的显示JavaScript警报的输出中。
  2. Using Response.Redirect to trigger an HTTP 302 redirect . 使用Response.Redirect触发HTTP 302重定向

The latter (2) means that (1) doesn't actually do anything. 后者(2)表示(1)实际上不做任何事情。 To achieve what you want here, you could send a script down using RegisterStartupScript like: 为了在这里实现您想要的,您可以使用RegisterStartupScript向下发送一个脚本,如下所示:

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

So you'd remove the Response.Redirect line and use: 因此,您将删除 Response.Redirect行并使用:

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

You can use a Timer in C#. 您可以在C#中使用Timer。 Just give the user enough time to read the message, then redirect your user to your desired page. 只需给用户足够的时间来阅读消息,然后将用户重定向到所需的页面即可。

This thread has a good example in using the timer: how to use Timer in C# 该线程有一个使用计时器的好例子: 如何在C#中使用Timer

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

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