[英]Retrieving Json Object from action method in ASP.NET
我已經搜索並看到了許多解決方案,但是仍然沒有任何進展。 我在控制台內沒有收到任何錯誤,也沒有從ajax請求中得到任何回報。
這是動作方法代碼:
[HttpGet]
public ActionResult GetEmployees()
{
AWEmployeeModel aw = new AWEmployeeModel();
aw.ID = 0;
aw.Name = "Selena";
aw.Position = "Cashier";
aw.Department = "Finance";
return Json(aw,JsonRequestBehavior.AllowGet);
}
這是我在控制器內的ajax調用:
EmpApp.controller("AWEmpControl", function ($scope) {
loadEmployees();
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.employees = response["Name"];
}
});
}
});
在所需頁面上也有ng指令:
<div class="container" ng-app="AWEmpApp" ng-controller="AWEmpControl">
{{employees}}
</div>
我通過分配$ scope.employees =“ Hello ...”;測試腳本是否可以正常工作; 沒問題,所以我知道這與腳本加載無關。...可能是什么問題? 我已經確保將請求描述為GET並返回一個JSON對象。 我想念什么嗎?
提前致謝。
編輯
我檢查了firefox控制台並返回解析錯誤:在該位置找不到XML。
由於服務器返回JSON對象,我覺得很奇怪,所以我用以下代碼替換了ajax方法:
function loadEmployees() {
$http.get('/AWEmployee/Index/GetEmployees')
.then(function(response) {
$scope.employees =response;
});
};
現在響應是調用它的頁面(索引)的html數據,而不是JSON對象! 我假設的東西是在建議的通信之間發生的事情在這個崗位 。
當您使用JQuery從服務器而不是$http
服務獲取數據並且success
執行函數是異步執行時,AngularJS不會反映發生的任何更改來強制執行,只需將分配包裝到$apply
:
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.$apply(function(){
$scope.employees = response["Name"];
});
}
});
}
找出問題所在,這對我來說是一個簡單的錯誤。 我打電話給http:// localhost:53729 / AWEmployees / Index / GetEmployees ,這是錯誤的做法。 我取出了“索引”頁面,所以現在該URL看起來像http:// localhost:53729 / AWEmployees / GetEmployees ,它可以正常工作!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.