【问题标题】:Looping json data using AngularJS in Asp.net MVC在 Asp.net MVC 中使用 AngularJS 循环 json 数据
【发布时间】:2016-11-27 19:46:06
【问题描述】:

我正在尝试通过 ajax 获取记录并使用 AngularJS 显示。 但是我的代码甚至没有调用控制器操作

我正在尝试这段代码..

<div ng-controller="MyCtrl">
<div ng-repeat="result in products">
    {{result.ProductName}}
</div>
</div>

阿贾克斯:

function MyCtrl($scope) {
  $.ajax({
    url: "/Products/Get/",
    type: "POST",
    success: function (data) {
      // Success message
      var myApp = angular.module('myApp', []);
      $scope.products = data;
    },
    error: function () {
      // Fail message
    },
  });
}

我正在使用this post 使其工作。

【问题讨论】:

  • 你没有控制器MyCtrl

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


【解决方案1】:

你的方法是错误的。 您应该使用 angularJS 的控制器指令来调用服务以使用 json 数据。

<script type="text/javascript">
    var app = angular.module('myApp', []); 
    app.controller('MyCtrl', function ($scope, $http) {  
        $http.get('/Products/Get/').success(function (data) {  
            $scope.products = data;
        });
    });
</script>

几天前我也写过一篇同样的文章。 您可以通过here。这可能会有所帮助。

【讨论】:

  • 由于success弃用,您应该使用then 而不是success
【解决方案2】:

你需要在 angularjs 中声明 module 名称,并且不要忘记在你的 body 或 html 标记中添加模块名称..like this &lt;body data-ng-app="app"&gt; 然后试试这样:

<script>
var app = angular.module('app',[]);

app.controller('MyCtrl',function($scope,$http){

bindData();
function bindData(
    // it will be nice, if this code your separate to file service...    
    $http.get('/Products/Get').success(function (callBack) {  
            $scope.products = callBack.data;
    });
);
});

</script>

和这样的最佳实现:

// in controller, injected you service name like this..
app.controller('MyCtrl',function($scope,$http ,myServices){

bindData();
function bindData(
  var promiseGet = myServices.GetAll();
  promiseGet.then(function(callBack){ // success
    $scope.products = callBack.data;

   }     
 ,function(error){ // error
     console.log(error);
   });
 );    

});

app.service('myServices',function($http){
var vm = this;
vm.GetAll = function(){
         return $http.get('/Products/Get');
     }
});

如果您想在 ajax 函数中获取数据,请输入不是 POST..

【讨论】:

    猜你喜欢
    • 2015-09-28
    • 1970-01-01
    • 2020-04-08
    • 2016-10-04
    • 2017-11-23
    • 2016-06-05
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多