Search code examples
c#asp.netajaxpagemethods

how to pass a variable to a Page Method Success callback function


i'm using asp.net PageMethods.So here is the way i make a call to the method from javascript

function hello()
{
    var a =10;
    PageMethods.SaveData(JSON.stringify(basicInfo), SaveSuccessCallback, SaveFailedCallback);
}

And here is my success call back condition

    function SaveSuccessCallback(response) {
    //handle success code here
    ShowEdit();
}

Now i wanted to handle the ShowEdit() based on a variable a which is in the hello function. The issue is i don't know if its possible to pass a from hello to SaveSuccessCallback . Note: i can't make a global.


Solution

  • You can use a closure:

    var a = 10;
    PageMethods.SaveData(
        JSON.stringify(basicInfo),
        function(response) { 
            SaveSuccessCallback(response);
            ShowEdit(a);
        }, SaveFailedCallback);
    
    function SaveSuccessCallback(response) {
       //handle success code here
    }
    

    You may prefer to make this a bit cleaner by wrapping up the closure in another method:

    PageMethods.SaveData(
        JSON.stringify(basicInfo), SaveSuccessCallback(10), SaveFailedCallback);
    
    function SaveSuccessCallback(a) {
        return function(response) {
            //handle success code here
            ShowEdit(a);
        };
    }