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