Using WebApi & MVC 5 and
AngularJS v1.3.4
I have an API setup that has a FavoritesRepository
& IFavoritesRepository
& Ninject. This part is ok, I can retrieve Favorites by UserId or SearchId. My favorites list is an API built around a Search.cs
model:
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; }
}
}
In my DataLayer Directory I have the FavoritesRepository
& IFavoritesRepository
with the following Add & Delete method.
(The Add method works with Angular just fine):
/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;
}
}
}
I have a WebAPI Controller where the POST Method already adds a new Favorite. I have copied over the POST and changed it to delete and attempted trying to get it to work, but my real problem is figuring out what to do with Angular
/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);
}
}
On the Angular end we have the Index.cshtml page that is the root of the site and has within it a section of angular code. That section has two angular routes, one "#/"
which load the following angular template/view: favoritesView.html
& newFavoiteView.html
which has the angular route "#/newfavorite"
/ng-templates/favoritesView.html
Route: #/
<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
Route: #/newfavorite
<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>
Finally I have the Angular Modules and Controllers (Again, Everything is working except for the delete. I'm just not sure what I should be doing in my favoritesView.html and how it works with the controller. ALso is my WebApi controller and Repo setup correctly?
Module & Controllers /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 = "#/";
});
};
};
I have been thinking about this all night. This code came from a pluralisight video from Shawn Wildermuth and I changed it to work with ControllerAs
and got rid of the scope and for some reason I just don't know exactly how to setup the delete. ANy help or a push in the right direction would be much appreciated. I've got it this far I can't let a delete action defeat me.
ANSWER
The above code has been updated with the working version. The idea was to remove the form on the favoritesView.html
and just use an
<a href="javascript:void(0);" ng-click="vm.delete(s.searchId)">X</a>
To call the delete function. Omri not only helped me with the concept of how to get the parameter over to the function but also helped me write a function that would update the view to show the removed item. I am very thankful for his help. Please 1up his answer if you find this useful.
$http.delete("/api/favorites", vm.delFavorite)
to$http["delete"]("/api/favorites", vm.delFavorite)
– Omri Aharon Feb 27 at 8:15$http.delete(url)
where url contains the identifier should be the way to go. – Omri Aharon Feb 27 at 8:28