简体   繁体   中英

Javascript Event Handler to Fire C# Method

A .NET application I've been working on is hanging on a certain function call. I wanted to know if there is a way that the event handler can "fire" the C# function instead of calling it and waiting for a return; in other words, I need it to continue running Javascript code instead of waiting. How would I achieve this functionality?

Here is a code outline:

Javascript

// Fires on user scroll event
function ScrollHandler() {
    //...
    // Calls the following C# function when a user scrolls
    window.external.UserScroll();
}

// Called by C# function UpLoadJson()
function drawTimeline(JsonData) { 
    //...
}

C#

// Called by Javascript function ScrollHandler()
void UserScroll()
{
    //...
    UpLoadJson();
}

void UpLoadJson()
{
    //...
    browser.Document.InvokeScript("drawTimeline", new String[] {data});
}

Using " -> " to denote a function call, what I think is happening is:

ScrollHandler(/*JS*/) -> UserScroll(/*C#*/) -> UpLoadJson(/*C#*/) -> drawTimeline(/*JS*/)

But the Javascript can't run drawTimeline() because it is waiting for ScrollHandler() to return first; this can't return until drawTimeline() is called though. I need ScrollHandler() to return without waiting for a return from UserScroll() .

@fabjan Code:

    $(document).ready(function() {
        $.ajax({
            url: window.external.HandleScroll(left, right),
            type: "GET"
        })
        // seems like this part would be optional, since calling HandleScroll() will
        // result in the draw function if it needs to
        /*.done(function (jsondata) {
            drawTimeline(jsondata);
        })*/
        .fail(function (err) {
            alert(err.statusText);
        });
    });

Try to useJQuery Ajax get/post request and callback methods:

$.ajax({
    url: (your controller/actionname),
    type: "GET",
}).done(function (jsondata) {
    some code here...
}).fail(function (err) {
    alert(err.statusText);
});

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