【问题标题】:Angularjs Cannot Load Data in ASP .Net MVCAngularjs 无法在 ASP .Net MVC 中加载数据
【发布时间】:2015-04-30 20:18:27
【问题描述】:

我正在使用 ASP .Net MVC 学习 angularjs 框架。这些代码失败并且不加载也不绑定任何 json 数据。请问哪一个是错误的?

控制器:

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;
                });
        });
};

它不加载数据并且不显示错误。这是浏览器上显示的结果

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

【问题讨论】:

    标签: c# asp.net asp.net-mvc angularjs


    【解决方案1】:

    当您使用ng-app 指令时,您应该从$(document).ready(function () { 加载角度模块,它应该直接加载将解决您的问题

    Javascript

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

    Working DotNetFiddle这里

    【讨论】:

    • 非常感谢。它现在正在工作。我也犯了错误,将 ng-app 的两个 div 放在同一个 cshtml 页面中。但是,@Url.RouteUrl 如何生成数据而@Url.Action 不生成数据?谢谢
    • @derodevil 你可以看看这个stackoverflow.com/questions/15250186/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多