2016-05-31 50 views
0

我創建了一個小的MVC項目,我想通過我的JavaScript控制器檢索數據AngularJS與MVC ERR_CONNECTION_REFUSED

我的控制器看起來是這樣的: -

angular.module('MyApp', []) 
    .controller('PlayerCtrl', function ($scope, $http) { 
    $scope.title = "loading..."; 
    $scope.players = []; 
    $scope.working = false; 
    $scope.myString = "ABC"; 

    $scope.getPlayers = function (group) { 
     $scope.working = true; 

     $http.get("/api/player").success(function (data, status, headers, config) { 
      $scope.players = data.players; 

     }).error(function (data, status, headers, config) { 
      $scope.title = "Oops... something went wrong"; 
      $scope.working = false; 
     }); 
    }; 

}); 

我的HTML頁面看起來像這樣: -

@{ 
    ViewBag.Title = "Play"; 
} 

<div id="bodyContainer" ng-app="MyApp"> 
    <section id="content"> 
    <div ng-model="PlayerCtrl" ng-init="getPlayers()"> 
     <p>{{myString}}</p> 
     <select id="group1"> 
      <option ng-repeat="option in data.players" value="{{option.FirstName}}">{{option.LastName}}</option> 
     </select> 
    </div> 
    </section> 
</div> 

@section scripts { 
    @Scripts.Render("~/Scripts/angular.js") 
    @Scripts.Render("~/Scripts/app/player-controller.js") 
} 

我可以看到我的JavaScript被擊中,因爲我已經在Chrome開發人員工具斷點

然而,當執行JavaScript的我在開發工具

http://localhost:61176/4181b55e60dd4855bf01360ebafcfd61/browserLink無法加載資源的控制檯收到以下錯誤:淨:: ERR_CONNECTION_REFUSED

我不知道爲什麼。任何指針極大讚賞

注 - 如果我添加/ api /播放器到我的URL測試然後我的.NET代碼觸發並正確執行。從javascript控制器正常運行時,我的.NET代碼不會被調用

回答

1

您沒有發佈您的控制器代碼,所以我不知道它是否相關,但請確保您的JSON操作設置爲JsonRequestBehavior.AllowGet
例如:

public JsonResult GetAllCustomers() 
{ 
    var customers = new List<Customer> 
    { 
     new Customer { Id = 1, Name = "a"}, 
     new Customer { Id = 2, Name = "b"}, 
     new Customer { Id = 3, Name = "c"}, 
     new Customer { Id = 4, Name = "d"} 
    }; 
    return Json(customers, JsonRequestBehavior.AllowGet); // here 
} 

,你應該在你是js代碼位於不同的域比你controller是,你必須啓用cors檢查的情況下另一件事。

0

我在我的div上錯誤地使用了ng-model而不是ng-controller。