我正在尝试使用angular-resource en asp.net webapi删除我的集合中的项目。调用正确的服务器端方法,但没有与它一起发送的对象:suitcase为null。
我的代码中缺少什么来处理发送对象?
角度代码:
var myApp = angular.module('myApp', ['ui.router', 'ngResource']);
myApp.config([
'$stateProvider', function($stateProvider) {
$stateProvider
.state('suitcases.delete', {
url: '/suitcase/delete/:id',
controller: 'deleteSuitcaseController'
});
}
]);
angular.module('myApp').controller('deleteSuitcaseController', function ($scope, $state, $stateParams, Entry) {
console.log('deleteSuitcaseController', $stateParams.id);
$scope.deleteSuitcase = function () {
var suitcase = Entry.get({ id: $stateParams.id });
suitcase.$delete();
};
$scope.deleteSuitcase();
});
angular.module('myApp').factory('Entry', function($resource) {
return $resource(
"api/suitcaseapi/:id", { id: '@@id' },
{ "update": { method: "PUT" } },
{ "add": { method: "POST" } }
);
});
webapi代码:
public class SuitcaseApiController : ApiController
{
public void Delete(Suitcase suitcase)
{
Singleton.Instance.Suitcases.RemoveAll(p => p.Id == suitcase.Id);
}
}
如果我将服务器端方法更改为下面的代码,我在浏览器中会出现405不允许的错误。
public void Delete(int suitcaseid)
{
Singleton.Instance.Suitcases.RemoveAll(p => p.Id == suitcaseid);
}
}
PS。我拿出了我认为无关的代码。
答案 0 :(得分:0)
如果它是删除,并且我可以看到你已经拥有了suitcaseId,则不需要调用API来返回整个对象只是为了删除它。只需传递Id,API就会找到实体。像这样:
角度控制器/功能
angular.module('myApp').controller('deleteSuitcaseController', function ($scope, $state, $stateParams, Entry) {
$scope.entity.id = $stateParams.id;
$scope.deleteSuitcase = function () {
$http.delete('/Suitcase/' + $scope.entity.id)
.success(function (data, status, headers) {
})
.error(function (data, status, header, config) {
});
}
});
删除方法API
public void Delete(int id)
{
Singleton.Instance.Suitcases.RemoveAll(p => p.Id == id);
}