简体   繁体   English

Angular从MVC JsonResult获取数据

[英]Angular get data from MVC JsonResult

I have the following Action in my MVC Controller: 我的MVC控制器中有以下Action:

[HttpPost]
public JsonResult Save(TestModel model)
{
    var newId = _myService.CreateItem(model);
    return Json(newId);
}

This runs and returns an ID, I see it returning in Fiddler for example as 42. However my angular code it doesn't get the number, but the returned value is shown as data : b, which contains a promise. 这会运行并返回一个ID,我看到它在Fiddler中返回,例如42.但是我的角度代码没有得到数字,但返回的值显示为data:b,其中包含一个promise。 Is there a way to get the number returned in the data of the success method? 有没有办法获取成功方法数据中返回的数字? My angular code is below: 我的角度代码如下:

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.');
    });
}

my service is 我的服务是

function TestRepository($resource) {
return {
    save: function (item) {
        return $resource('/mysite/setup/Save').save(item);
    }
}

The service is able to call the Action, as I see the code hit my breakpoints, I can see newId also set to 42, but I never see it come back in the angular side. 该服务能够调用Action,因为我看到代码点击我的断点,我可以看到newId也设置为42,但我从未看到它回到角度方面。

$resource doesn't support primitive response $resource不支持原始响应

As $resource generally used to connect with RESTFUL service, do send data in well formed object, that is how all API does. 由于$resource通常用于连接RESTFUL服务,请在格式良好的对象中发送数据,这就是所有API的工作方式。 Sending data from API in primitive type discourage people to use bad pattern. 从原始类型的API发送数据不鼓励人们使用坏模式。 Ideally it should only return JSON object. 理想情况下,它应该只返回JSON对象。

[HttpPost]
public JsonResult Save(TestModel model)
{
    var newId = _myService.CreateItem(model);
    return Json(new {Id = newId});
}

Code

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM