Reputation: 181
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;
}
Upvotes: 3
Views: 15536
Reputation: 329
Here, Simple Angularjs Ajax Call
to WebMethod
and get response
<div ng-app="myapp" ng-controller="MyController" >
<div ng-click="getData()">GetData</div> <br />
{{showData}}
</div>
_____________________________________________________
<script>
var test = angular.module("myapp", []);
test.controller("MyController", function ($scope, $http) {
$scope.getData = {};
$scope.getData = function () {
try {
// Call to Web Method
var httpRequest = $http({
method: "POST",
url: "AjaxCall.aspx/test",
dataType: 'json',
data: {}, //use if want send parameter :: data: {id:1},
headers: {
"Content-Type": "application/json"
}
});
// if success
httpRequest.success(function (data, status) {
$scope.showData = data.d;
console.log(JSON.parse(data.d)); // conversion string to json format
});
// if fail
httpRequest.error(function (data, status) {
$scope.status = status;
console.log(status);
});
}
catch (e) {
console.log(e + " Some Error");
}
};
});
</script>
Code behind page:
// AjaxCall.aspx.cs file
[WebMethod]
public static string test() // if parameterized call :: test(string id)
{
return "succeed";
}
Upvotes: 1
Reputation: 1258
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";
}
Upvotes: 7