C# 代码隐藏文件中的事件延迟
在我的应用程序中,我有一个按钮来保存一些信息。但是,我希望在执行最后一行之前代码中有一个延迟,这样用户就可以在重定向到新页面之前阅读显示的消息 我知道这样做根本不是一种最佳方式,但出于某些原因(比如时间),我还是想这样做 那么有可能吗?如果有,我该怎么做 提前谢谢C# 代码隐藏文件中的事件延迟,c#,asp.net,events,delay,C#,Asp.net,Events,Delay,在我的应用程序中,我有一个按钮来保存一些信息。但是,我希望在执行最后一行之前代码中有一个延迟,这样用户就可以在重定向到新页面之前阅读显示的消息 我知道这样做根本不是一种最佳方式,但出于某些原因(比如时间),我还是想这样做 那么有可能吗?如果有,我该怎么做 提前谢谢 protected void SaveButton_Click(object sender, EventArgs e) { // Lots of code not relevant for the problem here
protected void SaveButton_Click(object sender, EventArgs e) {
// Lots of code not relevant for the problem here
Service service = new Service();
service.SaveMovie(movie);
successMessage.Visible = true;
happyMessage.Text = "The movie was successfully added, now add some genres!";
// Here I want a delay of 2 seconds before the next line is executed...
Response.Redirect(String.Format("~/Edit.aspx?id={0}", movie.MovieID), false);
}
您需要在客户端执行此操作。另一种选择是: 在名为
redirect
的页面中定义Javascript
函数,如下所示:
function redirect(url)
{
setTimeout(function(){window.location.href=url;} ,2000);
}
protected void SaveButton_Click(object sender, EventArgs e)
{
// Lots of code not relevant for the problem here
Service service = new Service();
service.SaveMovie(movie);
successMessage.Visible = true;
happyMessage.Text = "The movie was successfully added, now add some genres!";
// Here I want a delay of 2 seconds before the next line is executed...
ClientScript.RegisterStartupScript(this.GetType(),"somekey","redirect('"+String.Format("~/Edit.aspx?id={0}", movie.MovieID)+"');");
}
如果您使用的是Javascript,这将很容易。使用javascript将提高性能
Button_Click
{
string js ="<script type='text/javascript'>setTimeout(function()window.location.href="+String.Format("~/Edit.aspx?id={0}", movie.MovieID)+";} ,2000);</script>"
可能重复的
他们永远不会看到消息文本。在响应重定向之前只会有2秒的延迟。这里需要一些JavaScript(jQuery)。是的,但我可以将其更改为5秒或10秒。问题是它是否可能以及如何实现。@HenkHolterman:实际上,我在这里使用jQuery是在5秒后删除div“successMessage”。问题是,在这种情况下,重定向不会等待5秒。非常感谢您的回答。但是,在实现代码时,我收到以下错误消息:“错误1非静态字段、方法或属性'System.Web.UI.ClientScriptManager.RegisterStartupScript(System.Type,string,string)]需要对象引用。”。你知道怎么解决吗?@JasonCraig我更新了我的答案。试试
ClientScript.RegisterStartupScript(…)
。好的,谢谢。问题是,现在我收到了以下错误消息:“名称'ClientScript'在当前上下文中不存在”。:/@JasonCraig LOL,是ClientScriptManager还是ClientScript。如果您使用的是.NET 4.0,则应该能够执行此操作。ClientScript.RegisterStartupScript但是此
显然不是必需的,因此如果此代码位于页面内,则调用ClientScript应该可以。如果代码在用户控件中,那么您应该能够执行this.Page.ClientScript
哦,对不起。不,它不在第页,所以这页。。。工作。但是,当运行我的应用程序时,代码不会被执行,而是在网页上显示为文本:“重定向('~/Edit.aspx?id=53');”:SThanks alot!但是,我在ClientScriptManager中发现编译错误。。。错误1非静态字段、方法或属性“System.Web.UI.ClientScriptManager.RegisterStartupScript(System.Type,string,string)”需要对象引用。你知道怎么解决吗?这是错误的。您不能调用System.Threading.Thread.Sleep(5000)来实现用户想要的功能。这将阻止响应5秒钟,然后吐出整个HTML。我认为有可能将5000减少到某个较低的值value@Harie事实上,谢谢你把另一个问题联系起来。Rahul Sony提供的答案也是错误的。我投了反对票。@Harie你不明白。如果您愿意,可以将其缩短为1秒。关键是用户希望显示一条消息,然后在重定向之前等待。如果调用Thread.Sleep将阻止响应,则在第二次调用结束之前不会写入任何内容。然后,用户将在能够看到任何消息之前立即被重定向。
}