[英]Angular get data from MVC JsonResult
我的MVC控制器中有以下Action:
[HttpPost]
public JsonResult Save(TestModel model)
{
var newId = _myService.CreateItem(model);
return Json(newId);
}
這會運行並返回一個ID,我看到它在Fiddler中返回,例如42.但是我的角度代碼沒有得到數字,但返回的值顯示為data:b,其中包含一個promise。 有沒有辦法獲取成功方法數據中返回的數字? 我的角度代碼如下:
vm.save = function () {
TestRepository.save(vm.MyData).$promise.then(
function (data) {
// Here data is returned as data : b, not the number
},
function () {
alert('An error occurred while creating this record.');
});
}
我的服務是
function TestRepository($resource) {
return {
save: function (item) {
return $resource('/mysite/setup/Save').save(item);
}
}
該服務能夠調用Action,因為我看到代碼點擊我的斷點,我可以看到newId也設置為42,但我從未看到它回到角度方面。
由於$resource
通常用於連接RESTFUL服務,請在格式良好的對象中發送數據,這就是所有API的工作方式。 從原始類型的API發送數據不鼓勵人們使用壞模式。 理想情況下,它應該只返回JSON
對象。
[HttpPost]
public JsonResult Save(TestModel model)
{
var newId = _myService.CreateItem(model);
return Json(new {Id = newId});
}
碼
vm.save = function () {
TestRepository.save(vm.MyData).$promise.then(
function (data) {
console.log(data.Id)
},
function () {
alert('An error occurred while creating this record.');
}
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.