【发布时间】:2015-05-12 17:23:53
【问题描述】:
我正在尝试使用由存储库模式支持的 Web API 控制器来了解更新数据库的基本知识。到目前为止,我已经完成了 POST、GET、DELETE(创建、读取、删除)的一切工作。但我错过了更新。
以下是我的 Angular 代码,我不打算发布 Angular 视图/模板,但只知道它们确实绑定并且工作正常。我的问题仅在编辑视图上,我尝试使用vm.save 函数进行更新。我的保存功能在 Angular 端运行良好,但我不确定在 Web API 和存储库端该怎么做。你会看到我的代码让这个工作是非常基本的。我的项目中的所有代码页都在这里:
以防万一你想看大图,否则我只会放在这里我无法让编辑/更新方法在使用 http.put 与 Angular 控制器、Web API 控制器和存储库.
工作 Angular 编辑控制器:
function editFavoriteController($http, $window, $routeParams) {
var vm = this;
var url = "/api/favorites/" + $routeParams.searchId;
$http.get(url)
.success(function (result) {
vm.search = result[0];
})
.error(function () {
alert('error/failed');
})
.then(function () {
//Nothing
});
vm.update = function (id) {
var updateUrl = "/api/favorites/" + id;
$http.put(updateUrl, vm.editFavorite)
.success(function (result) {
var editFavorite = result.data;
//TODO: merge with existing favorites
//alert("Thanks for your post");
})
.error(function () {
alert("Your broken, go fix yourself!");
})
.then(function () {
$window.location = "#/";
});
};
};
Web API 控制器不起作用
public HttpResponseMessage Put(int id,[FromBody]Search editFavorite)
{
if (_favRepo.EditFavorite(id, editFavorite) && _favRepo.Save())
{
return Request.CreateResponse(HttpStatusCode.Created, editFavorite);
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
不工作的存储库
public bool EditFavorite(int id, Search editFavorite)
{
try
{
var search = _ctx.Search.FirstOrDefault(s => s.SearchId == id);
search(editFavorite).State = EntityState.Modified;
return true;
}
catch
{
var item = "";
}
}
工作界面
bool EditFavorite(int id, Search newSearch);
同样,我唯一的问题是弄清楚如何在 WebAPI FavoritesController 和 FavoritesRepository 中进行更新。我有示例说明我如何在 Gist 中完成其他所有操作,因此我希望有人能够帮助我。我只是碰壁了我知道如何在 Web API 中做的事情。
【问题讨论】:
-
editFavorite 参数是否为空?传入请求中的 Content-Type 标头是否设置正确?
-
我不熟悉 .Name(...) 的作用,但我认为应该是 _ctx.Entry(editFavorite).State = EntityState.Modified;示例参考msdn.microsoft.com/en-au/data/jj592676.aspx
-
我可以再次检查,但我认为一切正常,我的问题是我之前从未实施过更新请求,我无法弄清楚如何设置我的 PUT 操作和我在存储库端的编辑方法。我发送的 id 和 editFavorite 对象与我在其他场合使用删除或添加相同。并且我会确保按照您的要求正常工作,但我的主要问题是我只是在黑暗中刺伤,以了解在 C# 方面为这次更新做些什么。
-
如果您通过了有效的 editFavourite 对象,那么我认为您的 WebAPI 代码没有任何问题。我无法帮助您的 EF/Repository 代码。我也不明白那个 search.Name(.. line of code.
-
哎呀,这是我的错字。让我解决这个问题。
标签: javascript c# angularjs asp.net-web-api asp.net-mvc-5