Calling WebMethod Using AngularJS

This blog will demonstrate how users can call Webmethod using AJAX request in AngularJS.

Let's declare a webmethod which returns the string value "Hello World" in the code behind file 'Sample.aspx,cs'.

  1. public partial class Sample: System.Web.UI.Page {  
  2.     protected void Page_Load(object sender, EventArgs e) {}  
  3.   
  4.     [WebMethod]  
  5.     public static string GetEmployees() {  
  6.         return "Hello World";  
  7.     }  
  8. }  
HTML Code for 'Sample.aspx' is as follows:
  1. <html>  
  2.     <head>  
  3.         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>  
  4.         <script>  
  5. angular.module("myapp", [])  
  6. .controller("MyController", function ($scope, $http) {  
  7. $scope.retData = {};  
  8. $scope.retData.getResult = function (item, event) {  
  9. $http.post('Sample.aspx/GetEmployees', { data: {} })  
  10. .success(function (data, status, headers, config) {  
  11. $scope.retData.result = data.d;  
  12. })  
  13. .error(function (data, status, headers, config) {  
  14. $scope.status = status;  
  15. });  
  16. }  
  17. }).config(function ($httpProvider) {  
  18. $httpProvider.defaults.headers.post = {};  
  19. $httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";  
  20. });  
  21. </script>  
  22.     </head>  
  23.     <body ng-app="myapp">  
  24.         <div ng-controller="MyController">  
  25.             <button ng-click="retData.getResult(item, $event)">Send AJAX Request</button>  
  26.             <br />  
  27. Result from server: {{retData.result}}  
  28.   
  29.         </div>  
  30.     </body>  
  31. </html>  
Run the page and click on the button 'Send AJAX Request'.

You will get the string returned from server webmethod.

Happy Coding.