Pergunta

I was wondering. I tried googling for answers but they don't give me answers. Thanks.

Foi útil?

Solução

Yes, an ASP.NET AJAX Page Method will continue execution after a user leaves a page, but the result (if any) will not come back to the page, since the page where the request was initiated is now gone.

For example:

Code-behind on Default.aspx page:

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string GetHelloWorld()
    {
        Thread.Sleep(20000);
        return "Hello World";
    }

    protected void ButtonContactRedirect_OnClick(object sender, EventArgs e)
    {
        Response.Redirect("Contact.aspx");
    }
}

Markup on Default.aspx page:

<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetHelloWorld",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                alert(msg);
            }
        });
    });
</script>
<asp:Button runat="server" ID="ButtonContactRedirect" Text="Go to Contacts Page" OnClick="ButtonContactRedirect_OnClick"/>

So we have a button on Default.aspx that will redirect to another page (Contacts.aspx) when the user clicks it. Meanwhile, when Default.aspx is loaded, there is an AJAX call to the page method that sleeps for 20 seconds before returning the string Hello World.

If you put a break point on the following line:

return "Hello World";

When you run the program and the page loads, if you do not click the button for 20 seconds then the AJAX success callback will fire and an alert will show the string object returned. If you press the button before the 20 second sleep finishes, then the Redirect() will happen and the Contacts.aspx page will load, but the break point will be hit once the sleep finishes; however the returned Hello World string will be lost, because the AJAX context was tied to the Default.aspx page and not the Contacts.aspx page, which is now gone.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top