Koos Dup

Koos Dup

  • NA
  • 19
  • 5.2k

Angular function call to ASP.net web method

Sep 23 2017 2:33 AM
Hi
I want to call a webmethod on an ASP.net app from angular and I am doing something wrong. The webmethod must return a collection (of students)
 
Server side:
[System.Web.Services.WebMethod]
public static void Method3(int myIntPar, string myStringPar)
{
   var js = new JavaScriptSerializer();
   var context = HttpContext.Current;
   context.Response.Write(js.Serialize(new Student() { Id = 1, Surname = "Botha" }));
}
 
Here is my angular function inside the controller:
   $scope.myFunction = function () {
      $http({
                  method: "POST",
                  url: "my url/WebForm1.aspx/Method3",
                  dataType: 'json',
                  data: { myIntPar: 5, myStringPar: "test" },
                  headers: { "Content-Type": "application/json" },
                  contentType: "application/json; charset=utf-8"
               })
      .then(function (response) {
            $scope.students = response.data.d;
      },
      function (message) {
            console.log(message);
      });
};
 
 The serverside method is called and everything looks ok on that side.
On the client's side, I get the following error: 
  
Error: [$http:baddata] Data must be a valid JSON object. Received: "{"Id":1,"Surname":"Botha"}{"d":null}". Parse error: "{}"
http://errors.angularjs.org/1.6.6/$http/baddata?p0=%7B%22Id%22%3A1%2C%22Surname%22%3A%22Botha%22%7D%7B%22d%22%3Anull%7D&p1=%7B%7D
at angular.js:116
at defaultHttpResponseTransform (angular.js:11316)
at angular.js:11409
at forEach (angular.js:410)
at transformData (angular.js:11408)
at transformResponse (angular.js:12250)
at processQueue (angular.js:17051)
at angular.js:17095
at Scope.$digest (angular.js:18233)
at Scope.$apply (angular.js:18531)
 

Answers (1)