在Angular和.Net MVC 5 / Web API中使用http.delete

时间:2015-02-27 08:12:22

标签: javascript angularjs asp.net-web-api asp.net-mvc-5 http-delete

使用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方法适用于Angular):

/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;
    }
  }
}

我有一个WebAPI控制器,其中POST方法已经添加了一个新的收藏夹。我复制了POST并将其更改为删除并试图让它工作,但我真正的问题是弄清楚如何处理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);
    }
}

在Angular端,我们有Index.cshtml页面,它是站点的根,并且在其中包含一段角度代码。该部分有两个角度路线,一个"#/"加载以下角度模板/视图:favoritesView.html&amp; 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
路线:#/ 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>

最后我有Angular模块和控制器(同样,除了删除之外,一切都在工作。我只是不确定我应该在我的favoritesView.html中做什么以及它如何与控制器一起工作。另外我的WebApi控制器和回购设置正确吗?

模块&amp;控制器 /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 Wildermuth的复数视频,我将其更改为与ControllerAs一起使用并摆脱了范围,由于某种原因,我只是不知道如何设置删除。任何帮助或推动正确的方向将非常感激。我到目前为止我不能让删除操作让我失望。


ANSWER 上面的代码已使用工作版本进行了更新。我们的想法是删除favoritesView.html上的表单,然后使用

<a href="javascript:void(0);" ng-click="vm.delete(s.searchId)">X</a>

调用删除功能。 Omri不仅帮助我了解如何将参数传递给函数的概念,还帮助我编写了一个更新视图以显示已删除项目的函数。我非常感谢他的帮助。如果你觉得这很有用,请给他一个答案。

1 个答案:

答案 0 :(得分:2)

由于评论过于繁忙,我将此作为答案总结:)

由于您在视图中有ng-model="vm.newFavorite.searchId",因此您可以获取searchId并使用它附加到网址:

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中的FavoritesController函数现在只需要一个searchId参数,因此您需要在客户端或服务器上更改名称,以便它们匹配,你肯定需要将服务器中变量的类型从Search更改为字符串或我假设的Guid。

编辑:在聊天讨论之后,我们得出结论删除表单元素,并只有一个按钮ng-click到删除功能。