Search code examples
asp.netwcfwebmethod

Unable to get data from ajax function call from WCF service in first attempt


[WebMethod]
public static string LoadAccount()
{
    address = new EndpointAddress(objClientSession.ServiceURL);
    proxy = new PMToolServices.MyAppServiceClient(binding, address);

    //Now call the web service to get the accounts
    proxy.wsGetAccountsCompleted += new EventHandler<MyAppServices.wsGetAccountsCompletedEventArgs>(proxy_wsGetAccountsCompleted);
    proxy.wsGetAccountsAsync();
    return strAccountList;
}

I am calling LoadAccount WebMethod using ajax. In LoadAccount I have added callback proxy_wsGetAccountsCompleted to wsGetAccounts of WCF. In proxy_wsGetAccountsCompleted I'm building result to return to LoadAccount. Issues:

  • I'm unable to return result directly from 'proxy_wsGetAccountsCompleted' so I've stored that result in global defined string and then at the end of LoadAccout WebMethod returning that. Can I return that directly from proxy_wsGetAccountsCompleted.

  • When I call LoadAccount WebMethod first time it returning blank result and if I call again second time then I get correct result. Even though as sequence I'm returning that global defined string after proxy_wsGetAccountsCompleted above it. Is that right?

Confused about sequence/return response between:

  • proxy.wsGetAccountsAsync();
  • proxy_wsGetAccountsCompleted();
  • return strAccountList

Solution

  • You are doing something strange: calling a wcf operation that is synchonous, that calls an asynchonous operations. Of course the first time it will not works.

    LoadAccount() returns prior to get the wsGetAccountsAsync() result. You can either call wsGetAccountsAsync in synchonous way or use an asynchonous operation, like using Signal R.

    Remember that when call the operation by the 2nd time, you will get result from previous request, if your method was accepting some parameter, you will store a wrong value, that is the response for your previous request.