简体   繁体   中英

Passing C# function return value to Javascript

what i'm doing is, i'm calling a C# function so it returns the data i will use in Javascript, However when i read the data from javascript it's always undefined, I debugged the C# function and found out that it actually returns the correct data, so i'm thinking i'm only having trouble receiving it from Javascript.

Here is the c# function i'm calling

  [WebMethod]
    public static string CommonBus(int StopNo1, int StopNo2)
    {
        JavaScriptSerializer oSerializer = new JavaScriptSerializer();
        LinkedList<int> StopBusNo1 = new LinkedList<int>();
        LinkedList<int> StopBusNo2 = new LinkedList<int>();

        StopBusNo1 = LookForBuses(StopNo1); //Returns the buses that stop at StopNo1
        StopBusNo2 = LookForBuses(StopNo2);

       LinkedList<int> CommonBusNos = LookForCommonBuses(StopBusNo1.First, StopBusNo2.First);// Get common buses that stop at both stops 
       LinkedListNode<int> commonNo = CommonBusNos.First;
       LinkedList<Bus> availableBus = new LinkedList<Bus>();

        while (commonNo != null)
        {
            availableBus.AddLast(GetCommonBusIntel(commonNo.Value, StopNo1, StopNo2));
            commonNo = commonNo.Next;
        }

        return oSerializer.Serialize(availableBus);
    }

And here is the Javascipt side

      function FindTransportation(startStops, endStops) {

      for (var i = 0; i < startStops.length; i++) {

          for (var x = 0; x < endStops.length; x++) {

              availabeTransports.push(PageMethods.CommonBus(startStops[i].StopNo, endStops[x].StopNo)); // Trying to push the returned data into an array


          }
      }
  }

Alright found the answer thank you for your comments.

i edited the FindTransportation function

   function FindTransportation(length1, length2) {
      for (var i = 0; i < length1; i++) {
          for (var x = 0; x < length2; x++) {                 
              GetCommonBuses(i, x);              
          }
      }
  }

and i also created the GetCommonBuses function for ajax calls

  function GetCommonBuses(index1,index2) {
      $.ajax({
          type: "POST",
          url: "/HomePage.aspx/CommonBus",
          data: JSON.stringify({ StopNo1: startWalkableStops[index1].StopNo, StopNo2: endWalkableStops[index2].StopNo }),
          contentType: "application/json; charset:utf-8",
          dataType: "json",
      })
          .done(function (res) {
              availabeTransports.push(res);
          });
  }

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