derodevil
derodevil

Reputation: 1069

Angularjs Cannot Load Data in ASP .Net MVC

I am learning angularjs framework with ASP .Net MVC. These codes fail and don't load nor bind any json data. Please, which one is incorrect?

Controller:

public JsonResult GetCustomers()
{
    Customer[] customers = new Customer[]
    {
        new Customer { Age = 52, Comments = "Hello World", Id = 1, Name = "Andrew Max" },
        new Customer { Age = 12, Comments = "Hello World", Id = 2, Name = "Michael Hearve" },
        new Customer { Age = 54, Comments = "Hello World", Id = 3, Name = "Best Regards" },
        new Customer { Age = 33, Comments = "Hello World", Id = 4, Name = "Andrea Lucy" },
        new Customer { Age = 46, Comments = "Hello World", Id = 5, Name = "Silvia Reagen Estongard" },
        new Customer { Age = 23, Comments = "Hello World", Id = 6, Name = "James Hall" },
        new Customer { Age = 43, Comments = "Hello World", Id = 7, Name = "Pak Marsudi" },
        new Customer { Age = 22, Comments = "Hello World", Id = 8, Name = "Gilbert Silalahi" },
        new Customer { Age = 52, Comments = "Hello World", Id = 9, Name = "Noni Cukong" },
    };
    return Json(customers, JsonRequestBehavior.AllowGet);
}

HTML:

<div ng-app="app" ng-controller="angularController">
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Age</th>
                <th>Comments</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in items">
                <td>{{item.Id}}</td>
                <td>{{item.Name}}</td>
                <td>{{item.Age}}</td>
                <td>{{item.Comments}}</td>
            </tr>
        </tbody>
    </table>
</div>

Javascript:

$(document).ready(function () {
    test();
});

function test() {
    angular
        .module('app', [])
        .controller('angularController', function ($scope, $http) {
            $http.get("/Home/GetCustomers/")
                .success(function (data) {
                    $scope.items = data;
                });
        });
};

It doesn't load data and shows no errors. Here's the result displayed on browser

{{item.Name}} {{item.Age}} {{item.Comments}}

Upvotes: 2

Views: 1797

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

As you use ng-app directive you should load angular module from $(document).ready(function () { it should loaded directly will solve your issue

Javascript

angular
    .module('app', [])
    .controller('angularController', function ($scope, $http) {
        $http.get("/Home/GetCustomers/")
            .success(function (data) {
                $scope.items = data;
            });
    });

Working DotNetFiddle Here

Upvotes: 1

Related Questions