Search code examples
c#javascriptasp.netwebmethod

undefined value when calling server code from javascript in asp.net


I'm calling a server method from javascript. I've tested the server method and it works correctly. when I call the server method from javascript i get an undefined value instead of true of false. Can anyone tell me how to get the correct value?

this is the javascript method I am calling

function IsElectronic(programId) {
    var isElectronic = PageMethods.IsElectronic(programId);
    alert(isElectronic); //  The alert says undefined
    return isElectronic;
}

Server side call - this method works correctly

[System.Web.Services.WebMethod]
public static bool IsElectronic(long programId) {
    var taskProcessor = new TaskBL();
    var IsElectronic = taskProcessor.GetDelieveryType(programId).ContainsValue("ELECTRONIC");
    if (IsElectronic) {
        return true;
    } else {
        return false;
    }
}

Solution

  • Calling a webservice is an asynchronous operation. To get the result you have to use a callback.

    function IsElectronic(programId) {
        PageMethods.IsElectronic(programId, function(result) {
            alert(result); // true
        });
        // you cannot return a value, there isn't one yet
        //return isElectronic;
    }