Friday, June 12, 2015

Retrieve Data in Angular Js from Web Api as HttpResponseMessage


<!DOCTYPE html>
<html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

    <div ng-app="myApp" ng-controller="customersCtrl">

        <ul>
            <li ng-repeat="x in names">
                {{ x.Name + ', ' + x.Country }}
            </li>
        </ul>

    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('customersCtrl', function ($scope, $http) {
            $http.get("/api/Home/getperson").success(function (data) {
                alert(JSON.stringify(data));
                $scope.names = data;
            });
        });
    </script>

</body>
</html>






    public class records
    {
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }
    public class HomeController : ApiController
    {
        public HttpResponseMessage getperson()
        {
            var data = new List();
            records item1 = new records();
            item1.Name = "Name1";
            item1.City = "City1";
            item1.Country = "Country1";
            data.Add(item1);
            records item2 = new records();
            item2.Name = "Name2";
            item2.City = "City2";
            item2.Country = "Country2";
            data.Add(item2);
            records item3 = new records();
            item3.Name = "Name3";
            item3.City = "City3";
            item3.Country = "Country3";
            data.Add(item3);

            return Request.CreateResponse(HttpStatusCode.OK, data);
        }
    }

No comments:

Post a Comment