简体   繁体   中英

Calling jQuery's .ajax() from an eventHandler in c# Asp.Net

In the code behind ( upload.aspx ) I have an event that returns the number of bytes being streamed; and as I debug it, it works fine. I wanted to reflect the numbers returned from the event-handler on a progress bar and this is where I got lost. I tried using jQuery's .ajax() function. this is how I implemented it:

In the EventHandler in my code behind I added this code to call the .ajax() function:

Page.ClientScript.RegisterStartupScript(this.GetType(), "UpdateProgress", "<script type='text/javascript'>updateProgress();</script>");

My plan is whenever the eventHandler function changes the values of bytes being streamed it calls the javascript function "updateProgress()"

The .ajax() function "UpdateProgress()" is as:

function updateProgress() {

        $.ajax({
            type: "POST",
            url: "upload.aspx/GetData",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            success: function (msg) {

                $("#progressbar").progressbar("option", "value", msg.d);

            }
        });
    }

I made sure that the function GetData() is [System.Web.Services.WebMethod] and that it is static as well. so the workflow of what I am trying to implement is as: - Click On Upload button - The Behind code starts executing and EventHandler triggers - The EventHandler calls .ajax() function - The .ajax() function retrieves the bytes being streamed and updates progress bar.

When I ran the code; all runs well except that the .ajax() is only executed when upload is finished (and progress bar also updates only when finished upload); even though I call .ajax() function every time in the eventHandler function as reflected above...

What am I doing wrong? Am I thinking of this right? is there anything else I should add maybe an updatePanel or something?

Try this once:

$("#progressbar").progressbar({
    value: 0
});

$("#btnUpload").click(function() {
    var intervalID = setInterval(updateProgress, 250);
    $.ajax({
        type: "POST",
        url: "upload.aspx/GetData",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        success: function(msg) {
            $("#progressbar").progressbar("value", 100);
            clearInterval(intervalID);
        }
    });
    return false;
});

function updateProgress() {
    var value = $("#progressbar").progressbar("option", "value");
    if (value < 100) {
        $("#progressbar").progressbar("value", value + 1);
    }
}​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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