In this article I will explain with an example, how to call
WebMethod (PageMethod) using
AngularJS,
AJAX and JSON in ASP.Net using C# and VB.Net.
HTML Markup
The following HTML Markup consists of:
DIV – For applying
ng-app and
ng-controller AngularJS directives.
TextBox – For capturing Name.
The HTML TextBox has been assigned with an
AngularJS ng-model directive.
Button – For displaying Name and Current Server Time.
The Button has been assigned with an
AngularJS ng-click directive.
<div ng-app="MyApp" ng-controller="MyController">
Name:
<input type="text" ng-model="Name" />
<br />
<br />
<input type="button" value="Submit" ng-click="ButtonClick()" />
</div>
Calling WebMethod (PageMethod) using AngularJS, AJAX and JSON
Inside the
ButtonClick function, the
$http service is used to make an
AJAX call to the ASP.Net
WebMethod.
The $http service has following properties and events:
Properties
method – The method type of HTTP Request i.e. GET or POST. Here it is set to POST.
dataType – The format of the data i.e. XML or JSON. Here it is set to JSON.
data – The parameters to be sent to the
WebMethod.
headers – List of headers to be specified for the HTTP Request.
Events
1. success – This event handler is triggered once the
AJAX call is successfully executed.
2. error – This event handler is triggered when the
AJAX call encounters an error.
The response from the
AJAX call is received in JSON format inside the
Success event handler of the
$http service and the result is displayed using JavaScript Alert Message Box.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.ButtonClick = function () {
var post = $http({
method: "POST",
url: "Default.aspx/GetCurrentTime",
dataType: 'json',
data: { name: $scope.Name },
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
$window.alert(data.d);
});
post.error(function (data, status) {
$window.alert(data.Message);
});
}
});
</script>
Namespaces
You will need to import the following namespace.
C#
using System.Web.Services;
VB.Net
Imports System.Web.Services
Server Side WebMethod (PageMethod)
Inside the
WebMethod, the value of the
Name parameter received from the
AngularJS method is returned along with the Current Server Time.
C#
[WebMethod]
public static string GetCurrentTime(string name)
{
string message = "Hello ";
message += name;
message += "\nCurrent Time: ";
message += DateTime.Now.ToString();
return message;
}
VB.Net
<WebMethod>
Public Shared Function GetCurrentTime(name As String) As String
Dim message As String = "Hello "
message &= name
message &= vbCrLf & "Current Time: "
message &= DateTime.Now.ToString()
Return message
End Function
Screenshot
Demo
Downloads