Amaan Khan Amaan Khan - 4 months ago 74
AngularJS Question

Get Json Data From Asp.Net Webmethod and Consume in angularJS

Can any one guide me how to get json data from asp.net webmethod, and consume it in angularJS.

app.controller('MainController', ['$scope', function ($scope, $http) {
try {
$http({ method: 'GET', url: 'ProblemList.aspx/GetProblemList' })
.success(function (data, status, headers, config) {
alert(data); }).error(function (data, status, headers, config) {
});
} catch (e) {
throw e;
}

Answer

I had the same issue, I tried many different ways, this is the way I found it works... ( I think the tricks is a combination of the header config, and the json parameter with "data : {}", I am not sure but It was really tricky )

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestAngular.aspx.cs" Inherits="COEWebApp.NCoe.Employees.TestAngular" %>

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>

<body ng-app="myapp">

  <div ng-controller="MyController" >
    <button ng-click="myData.doClick(item, $event)">Send AJAX Request</button>
    <br/>
    Data from server: {{myData.fromServer}}
  </div>

  <script>
      angular.module("myapp", [])
          .controller("MyController", function ($scope, $http) {
              $scope.myData = {};
              $scope.myData.doClick = function (item, event) {

                  $http.post('TestAngular.aspx/GetEmployees', { data: {} })
                    .success(function (data, status, headers, config) {
                        $scope.myData.fromServer = data.d;
                    })
                    .error(function (data, status, headers, config) {
                        $scope.status = status;
                    });

              }


          }).config(function ($httpProvider) {

              $httpProvider.defaults.headers.post = {};

              $httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";

          });
  </script>

</body>

</html>

And on the same aspx page on the codebehid this is the simple code...

[WebMethod]
public static string GetEmployees()
{
  return "OK-test";
}
Comments