1

I have the following Action in my MVC Controller:

[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. 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.

2
  • Can you post the result of console.log(data); Commented Apr 28, 2016 at 15:02
  • @Hackerman that prints out b {$promise: d, $resolved: true} If I return an object instead of just the number it works, data contains the object, maybe the number is not getting sent back as JSON, as Fiddler shows the response back is just 42, not in JSON format. Commented Apr 28, 2016 at 15:10

1 Answer 1

3

$resource doesn't support primitive response

As $resource generally used to connect with RESTFUL service, do send data in well formed object, that is how all API does. Sending data from API in primitive type discourage people to use bad pattern. Ideally it should only return JSON object.

[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.');
        }
    );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.