2016-06-11 59 views
1

我是新的在MVC中使用角度,我正在從我的控制器使用ASP.NET MVC EF,角度讀取數據。 我嘗試用這樣的:AngularJS和Asp.Net之間的連接MVC

我在MVC控制器添加(路徑爲「/Controllers/BrandController.cs」)此代碼:

public JsonResult GetBrands() 
     { 
      var result = db.Brands.ToList(); 
      return Json(result, JsonRequestBehavior.AllowGet); 
     } 

然後在文件JS我把兩個服務和角度控制器,即代碼:

var BrandApp = angular.module('BrandApp', []); 

//Controller 
BrandApp.controller('BrandController', function ($scope, BrandService) { 

    getBrands(); 
    function getBrands() { 
     BrandService.getBrands() 
      .success(function (items) { 
       $scope.brands = items; 
       console.log($scope.brands); 
      }) 
      .error(function (error) { 
       $scope.status = 'Unable to load customer data: ' + error.message; 
       console.log($scope.status); 
      }); 
    } 

}); 

//service 
BrandApp.factory('BrandService', ['$http', function ($http) { 

    var BrandService = {}; 
    BrandService.getBrands = function() { 
     return $http.get('/Home/GetBrands'); 
    }; 
    return BrandService; 

}]); 

我錯了什麼?

謝謝你的答案!

回答

1

由於控制器名稱爲BrandController,所以URL應爲/Brand/GetBrands

BrandService.getBrands = function() { 
    return $http.get('/Brand/GetBrands'); 
}; 

通常情況下,當你處理那樣的問題,你想用FiddlerChrome Plugin PostMan,或其他一些工具來調試。

+0

非常感謝! – Dona

0

如果您的C#控制器是'BrandController',那麼URL應該是/ Brand/GetBrands。只需修改您的$ HTTP方法,像這樣:

BrandService.getBrands = function() { 
    return $http.get('/Brand/GetBrands'); 
}; 

這也是很好的做法,添加上述GetBrands方法[HttpGet]屬性。

+0

非常感謝你! – Dona

0

更改爲

return $http.get('/Brand/GetBrands'); 
+0

非常感謝! – Dona

0

贏是正確的。當你定義你的角度控制器時,我也會看到一個問題。 你有

BrandApp.controller('BrandController', function ($scope, BrandService) { 
... 
}) 

而且你應該有這樣的事情:

BrandApp.controller('BrandController', ['$scope', 'BrandService', function ($scope, BrandService) { ... }]) 

每次添加你必須將它添加到一個數組,它是第二個參數和參數列表的依賴該數組末尾的匿名函數。

而且你應該總是使用數組,即使你的控制器看起來像第二個參數:

MyApp.controller('MyController', [function() { ... }]) 

它只是更安全。如果我沒有記錯,某些版本的角色可能會因爲缺失而破裂(但並非總是)。