Search code examples
c#asp.neteventsdelay

Delay in event in code behind file


In my application I have a button to save some information. However, I would like to have a delay in the code before the last line is executed, so that the user could read the message that shows up before he gets redirected to the new page.

I know that doing this isn't at all an optimal way, but by some reasons (time, for example) I want to do it anyway.

So is it possible and if so, how could I do it?

Thanks in advance!

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

Solution

  • You need to do this on the client side. One alternative is this:

    Define a Javascript function in the page called redirect as so:

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