title: Using http.delete in Angular and .Net MVC 5 / Web API
body: <p><strong>Using WebApi &amp; MVC 5 and<br>
  <em>AngularJS v1.3.4</em></strong></p>
  
  <p>I have an API setup that has a <code>FavoritesRepository</code> &amp; <code>IFavoritesRepository</code> &amp; Ninject. This part is ok, I can retrieve Favorites by UserId or SearchId. My favorites list is an API built around a <code>Search.cs</code> model:</p>
  
  <pre><code>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; }
    }
  }
  </code></pre>
  
  <p>In my DataLayer Directory I have the <code>FavoritesRepository</code> &amp; <code>IFavoritesRepository</code> with the following Add &amp; Delete method.<br>
  (The Add method works with Angular just fine):</p>
  
  <p><strong>/DataLayer/IFavoritesRepository.cs</strong></p>
  
  <pre><code>namespace RenderLib.DataLayer
  {
    public interface IFavoritesRepository
    {
      IQueryable&lt;Search&gt; GetFavoritesByUserId(string id);
      IQueryable&lt;Search&gt; GetFavoriteBySearchId(int id);
  
      bool Save();
      bool AddFavorite(Search newSearch);
      bool DelFavorite(int id);
    }
  }
  </code></pre>
  
  <p><strong>/DataLayer/FavoritesRepository.cs</strong></p>
  
  <pre><code>namespace RenderLib.DataLayer
  {
    public class FavoritesRepository : IFavoritesRepository
    {
      RenderLibContext _ctx;
      public FavoritesRepository(RenderLibContext ctx)
      {
        _ctx = ctx;
      }
  
  
      public IQueryable&lt;Search&gt; GetFavoritesByUserId(string id)
      {
        return _ctx.Search.Where(s =&gt; s.UserId == id);
      }
  
      public IQueryable&lt;Search&gt; GetFavoriteBySearchId(int id)
      {
        return _ctx.Search.Where(s =&gt; s.SearchId == id);
      }
  
  
      public bool Save()
      {
        try
        {
          return _ctx.SaveChanges() &gt; 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 =&gt; s.SearchId == id));
        return true;
      }
    }
  }
  </code></pre>
  
  <p>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</p>
  
  <p><strong>/Controllers/Api/FavoritesController.cs</strong></p>
  
  <pre><code>public class FavoritesController : ApiController
  {
      private IFavoritesRepository _favRepo;
      public FavoritesController(IFavoritesRepository favRepo)
      {
          _favRepo = favRepo;
      }
  
      public IEnumerable&lt;Search&gt; Get()
      {
          var id = User.Identity.GetUserId();
          IQueryable&lt;Search&gt; results; 
          results = _favRepo.GetFavoritesByUserId(id);
  
          var favorites = results.OrderByDescending(s =&gt; s.UserId == id);
  
          return favorites;
      }
  
      public HttpResponseMessage Post([FromBody]Search newFavorite)
      {
          if (newFavorite.Created == null)
          {
              newFavorite.Created = DateTime.UtcNow;
          }
  
          if (_favRepo.AddFavorite(newFavorite) &amp;&amp; _favRepo.Save())
          {
              return Request.CreateResponse(HttpStatusCode.Created, newFavorite);
          }
          return Request.CreateResponse(HttpStatusCode.BadRequest);
      }
  
      public HttpResponseMessage Delete(Search id)
      {
          if (_favRepo.DelFavorite(id) &amp;&amp; _favRepo.Save())
          {
              return Request.CreateResponse(HttpStatusCode.Created, id);
          }
          return Request.CreateResponse(HttpStatusCode.BadRequest);
      }
  }
  </code></pre>
  
  <p>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 <code>"#/"</code> which load the following angular template/view: <code>favoritesView.html</code> &amp; <code>newFavoiteView.html</code> which has the angular route <code>"#/newfavorite"</code></p>
  
  <p><strong>/ng-templates/favoritesView.html</strong><br>
  <strong>Route: #/</strong></p>
  
  <pre><code>&lt;a class="tiny button radius" href="#/newfavorite"&gt;Add&lt;/div&gt;
  &lt;div class="small-12 column"&gt;
      &lt;div class="favContent"&gt;
          &lt;div class="search row" data-ng-repeat="s in vm.searches"&gt;
              &lt;div class="favName small-10 column"&gt;
                  &lt;a href="{{s.searchString}}"&gt;{{s.name}}&lt;/a&gt;
              &lt;/div&gt;
              &lt;div class="small-2 column"&gt;
                  &lt;a href="" ng-click="vm.delete(s.searchId)"&gt;
                      &lt;i class="fi-trash"&gt;&lt;/i&gt;
                  &lt;/a&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p><strong>/ng-templates/newFavoriteView.html</strong><br>
  <strong>Route: #/newfavorite</strong></p>
  
  <pre><code>&lt;div class="small-12 column"&gt;&lt;h3&gt;Saving Search&lt;/h3&gt;&lt;/div&gt;
  &lt;div class="small-12 column"&gt;
      &lt;form name="newFavoriteForm" novalidate ng-submit="vm.save()"&gt;
          &lt;input name="userId" type="hidden" 
                 ng-model="vm.newFavorite.userId" /&gt;
          &lt;input name="searchString" type="hidden" 
                 ng-model="vm.newFavorite.searchString" /&gt;
          &lt;label for="name"&gt;Name&lt;/label&gt;
          &lt;input name="name" type="text" 
                 ng-model="vm.newFavorite.name" autofocus/&gt;
          &lt;label for="description"&gt;Description&lt;/label&gt;
          &lt;textarea name="description" rows="5" cols="30" 
                    ng-model="vm.newFavorite.description"&gt;&lt;/textarea&gt;
          &lt;input type="submit" class="tiny button radius" value="Save" /&gt; | 
          &lt;a href="#/" class="tiny button radius"&gt;Cancel&lt;/a&gt;
      &lt;/form&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>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?</p>
  
  <p><strong>Module &amp; Controllers</strong>
  <strong>/ng-modules/render-index.js</strong></p>
  
  <pre><code>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 &lt; 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 = "#/";
              });
      };
  };
  </code></pre>
  
  <p>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 <code>ControllerAs</code> 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.</p>
  
  <hr>
  
  <p><strong>ANSWER</strong>
  The above code has been updated with the working version. The idea was to remove the form on the <code>favoritesView.html</code> and just use an </p>
  
  <pre><code>&lt;a href="javascript:void(0);" ng-click="vm.delete(s.searchId)"&gt;X&lt;/a&gt;
  </code></pre>
  
  <p>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.</p>