使用的WebApi & MVC 5和
AngularJS v1.3.4
我有一个API设置,它有一个FavoritesRepository & IFavoritesRepository & Ninject。这个部分没问题,我可以通过UserId或SearchId检索收藏夹。我最喜欢的列表是围绕Search.cs模型构建的API:
namespace RenderLib.Models
{
public class Search
{
public int SearchId { get; set; }
[MaxLength(128), Column(TypeName = "nvarchar")]
public string UserId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime? Created { get; set; }
[MaxLength(2080), Column(TypeName = "nvarchar")]
public string SearchString { get; set; }
}
}在我的DataLayer目录中,我使用了FavoritesRepository & IFavoritesRepository和下面的Add & Delete方法。
( Add方法的角度非常好):
/DataLayer/IFavoritesRepository.cs
namespace RenderLib.DataLayer
{
public interface IFavoritesRepository
{
IQueryable<Search> GetFavoritesByUserId(string id);
IQueryable<Search> GetFavoriteBySearchId(int id);
bool Save();
bool AddFavorite(Search newSearch);
bool DelFavorite(int id);
}
}/DataLayer/FavoritesRepository.cs
namespace RenderLib.DataLayer
{
public class FavoritesRepository : IFavoritesRepository
{
RenderLibContext _ctx;
public FavoritesRepository(RenderLibContext ctx)
{
_ctx = ctx;
}
public IQueryable<Search> GetFavoritesByUserId(string id)
{
return _ctx.Search.Where(s => s.UserId == id);
}
public IQueryable<Search> GetFavoriteBySearchId(int id)
{
return _ctx.Search.Where(s => s.SearchId == id);
}
public bool Save()
{
try
{
return _ctx.SaveChanges() > 0;
}
catch
{
// TODO log this error
return false;
}
}
public bool AddFavorite(Search newFavorite)
{
_ctx.Search.Add(newFavorite);
return true;
}
public bool DelFavorite(int id)
{
var search = _ctx.Search;
search.Remove(search.SingleOrDefault(s => s.SearchId == id));
return true;
}
}
}我有一个POST控制器,其中POST方法已经添加了一个新的WebAPI。我复制了这篇文章,并将其修改为删除,并试图让它发挥作用,但我真正的问题是弄清楚如何处理棱角。
/Controllers/Api/FavoritesController.cs
public class FavoritesController : ApiController
{
private IFavoritesRepository _favRepo;
public FavoritesController(IFavoritesRepository favRepo)
{
_favRepo = favRepo;
}
public IEnumerable<Search> Get()
{
var id = User.Identity.GetUserId();
IQueryable<Search> results;
results = _favRepo.GetFavoritesByUserId(id);
var favorites = results.OrderByDescending(s => s.UserId == id);
return favorites;
}
public HttpResponseMessage Post([FromBody]Search newFavorite)
{
if (newFavorite.Created == null)
{
newFavorite.Created = DateTime.UtcNow;
}
if (_favRepo.AddFavorite(newFavorite) && _favRepo.Save())
{
return Request.CreateResponse(HttpStatusCode.Created, newFavorite);
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
public HttpResponseMessage Delete(Search id)
{
if (_favRepo.DelFavorite(id) && _favRepo.Save())
{
return Request.CreateResponse(HttpStatusCode.Created, id);
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}在角端,我们有一个Index.cshtml页面,它是站点的根,其中包含一段角代码。该部分有两个角路径,一个"#/"加载以下角模板/视图:favoritesView.html & newFavoiteView.html,它有角路径"#/newfavorite"
/ng-templates/favoritesView.html
路线:#/
<a class="tiny button radius" href="#/newfavorite">Add</div>
<div class="small-12 column">
<div class="favContent">
<div class="search row" data-ng-repeat="s in vm.searches">
<div class="favName small-10 column">
<a href="{{s.searchString}}">{{s.name}}</a>
</div>
<div class="small-2 column">
<a href="" ng-click="vm.delete(s.searchId)">
<i class="fi-trash"></i>
</a>
</div>
</div>
</div>
</div>/ng-templates/newFavoriteView.html
路线:#/新喜爱的
<div class="small-12 column"><h3>Saving Search</h3></div>
<div class="small-12 column">
<form name="newFavoriteForm" novalidate ng-submit="vm.save()">
<input name="userId" type="hidden"
ng-model="vm.newFavorite.userId" />
<input name="searchString" type="hidden"
ng-model="vm.newFavorite.searchString" />
<label for="name">Name</label>
<input name="name" type="text"
ng-model="vm.newFavorite.name" autofocus/>
<label for="description">Description</label>
<textarea name="description" rows="5" cols="30"
ng-model="vm.newFavorite.description"></textarea>
<input type="submit" class="tiny button radius" value="Save" /> |
<a href="#/" class="tiny button radius">Cancel</a>
</form>
</div>最后,我有角模块和控制器(再次,所有的工作,除了删除。我只是不确定我应该在我的favoritesView.html中做什么,以及它如何与控制器一起工作。ALso是我的WebApi控制器和回购设置正确吗?
/ng-modules/render-index.js 模块与控制器
angular
.module("renderIndex", ["ngRoute","ngCookies"])
.config(config)
.controller("favoritesController", favoritesController)
.controller("newFavoriteController", newFavoriteController);
function config($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "/ng-templates/favoritesView.html",
controller: "favoritesController",
controllerAs: "vm"
})
.when("/newfavorite", {
templateUrl: "/ng-templates/newFavoriteView.html",
controller: "newFavoriteController",
controllerAs: "vm"
})
.otherwise({ redirectTo: "/" });
};
function favoritesController($http) {
var vm = this;
vm.searches = [];
vm.isBusy = true;
$http.get("/api/favorites")
.success(function (result) {
vm.searches = result;
})
.error(function () {
alert('error/failed');
})
.then(function () {
vm.isBusy = false;
});
vm.delete = function (searchId) {
var url = "/api/favorites/" + searchId;
$http.delete(url)
.success(function (result) {
var newFavorite = result.data;
//TODO: merge with existing topics
alert("Delete Successfull");
removeFromArray(vm.searches, searchId);
})
.error(function () {
alert("Your broken, go fix yourself!");
})
.then(function () {
$window.location = "#/";
});
};
};
function removeFromArray(items, searchId) {
var index;
for (var i = 0; i < items.length; i++) {
if (items[i].searchId == searchId) {
index = i;
break;
}
}
if (index) {
items.splice(index, 1);
}
}
function newFavoriteController($http, $window, $cookies) {
var vm = this;
vm.newFavorite = {};
vm.newFavorite.searchString = $cookies.currentSearch;
vm.newFavorite.userId = $cookies.uId;
vm.save = function () {
$http.post("/api/favorites", vm.newFavorite)
.success(function (result) {
var newFavorite = result.data;
//TODO: merge with existing topics
alert("Thanks for your post");
})
.error(function () {
alert("Your broken, go fix yourself!");
})
.then(function () {
$window.location = "#/";
});
};
};我一整晚都在想这个。这段代码来自Shawn的一个多视点视频,我将其更改为与ControllerAs一起工作,并去掉了范围,出于某种原因,我只是不知道如何设置删除。ANy的帮助或推动正确的方向将是非常感谢的。到目前为止,我不能让一个删除行动打败我。
答案上面的代码已经用工作版本更新了。其想法是删除favoritesView.html上的表单,只需使用
<a href="javascript:void(0);" ng-click="vm.delete(s.searchId)">X</a>调用delete函数。Omri不仅帮助我了解了如何将参数转换为函数的概念,而且还帮助我编写了一个函数,该函数将更新视图以显示已删除的项。我非常感谢他的帮助。如果你觉得这个有用的话,请把他的答案加起来。
发布于 2015-02-27 08:50:49
我会把这个总结成一个答案,因为评论太忙了:)
由于视图中有ng-model="vm.newFavorite.searchId",所以可以获取searchId,并使用它附加到url:
vm.delete = function (searchId) {
//API Controller will expect "/api/favorites/13" from an http delete
var url = "/api/favorites/" + searchId;
$http.delete(url)
.success(function (result) {
var newFavorite = result.data;
//TODO: merge with existing topics
alert("Delete Successfull");
removeFromArray(vm.searches, searchId);
})
.error(function () {
alert("Your broken, go fix yourself!");
})
.then(function () {
$window.location = "#/";
});
};};
注意,您的Delete函数现在只需要一个searchId参数,因此您需要在客户机或服务器上更改名称,以便它们匹配,并且您肯定需要将服务器中的变量类型从Search更改为string或Guid。
编辑:经过聊天讨论,我们得出了删除表单元素的结论,只有一个按钮和一个删除函数的ng-click。
https://stackoverflow.com/questions/28760281
复制相似问题