Blog Stats
  • Posts - 40
  • Articles - 0
  • Comments - 26
  • Trackbacks - 0

 

Consuming ASP.NET based JSON WebService in AngularJS

Step 1: Create a ASP.Net based WebService, which return data in JSON Format.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;

namespace SampleASPNETWebService
{
    /// <summary>
    /// Summary description for WebService
    /// </summary>
    [WebService(Namespace = "
http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {
        public class Employee
        {   
            public string Name { get; set; }   
        }

        [WebMethod]
        public void GetEmployees()
        {

            Employee[] emp1 = new Employee[] {

            new Employee()
            {
                Name="Jayant1",
            },
            new Employee()
            {
                Name="Jayant2",
            },
        };
            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(emp1));

        }

    }
}

Step 2: Create a HTML Page with following Code

<!DOCTYPE html>
<html>
<script src="
https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="mymodule" ng-controller="myController">

<table> 
    <thead> 
        <tr> 
            <th>Name</th>   
        </tr> 
    </thead> 
    <tbody> 
        <tr ng-repeat="employee in employees"> 
            <td> {{employee.Name}} </td>  
        </tr> 
    </tbody> 
</table>
</div>

<script>
    var mypartone = angular.module("mymodule", []).controller("myController", function($scope, $http) { 
        $http.post('WebService.asmx/GetEmployees').then(function (response) {
            response.ContentType = "application/json";
                    $scope.employees = response.data; 
            }); 
        }); 
</script>

</body>
</html>


Feedback

No comments posted yet.


Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

 

 

Copyright © Jayant Kumar