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'.
- public partial class Sample: System.Web.UI.Page {
- protected void Page_Load(object sender, EventArgs e) {}
-
- [WebMethod]
- public static string GetEmployees() {
- return "Hello World";
- }
- }
HTML Code for 'Sample.aspx' is as follows:
- <html>
- <head>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
- <script>
- angular.module("myapp", [])
- .controller("MyController", function ($scope, $http) {
- $scope.retData = {};
- $scope.retData.getResult = function (item, event) {
- $http.post('Sample.aspx/GetEmployees', { data: {} })
- .success(function (data, status, headers, config) {
- $scope.retData.result = 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>
- </head>
- <body ng-app="myapp">
- <div ng-controller="MyController">
- <button ng-click="retData.getResult(item, $event)">Send AJAX Request</button>
- <br />
- Result from server: {{retData.result}}
-
- </div>
- </body>
- </html>
Run the page and click on the button 'Send AJAX Request'.
You will get the string returned from server webmethod.
Happy Coding.