【问题标题】:Problem in calling delete action using Ajax in asp.net MVC在 asp.net MVC 中使用 Ajax 调用删除操作的问题
【发布时间】:2020-10-16 23:31:55
【问题描述】:

我正在使用 ajax 在我的 web api 控制器中调用删除操作。我有两种使用 Ajax 调用我的 api 的问题。

这是我的 api 代码:

[Authorize]
public class AttendancesController : ApiController
{
    private readonly ApplicationDbContext _context;

    public AttendancesController()
    {
        _context = new ApplicationDbContext();
    }

    [HttpDelete]
    public IHttpActionResult Delete(int gigId)
    {
        var userId = User.Identity.GetUserId();
        var attendance = _context.Attendances.SingleOrDefault(a => a.GigId == gigId && a.AttendeeId == userId);

        if (attendance == null)
        {
            return NotFound();
        }

        _context.Attendances.Remove(attendance);
        _context.SaveChanges();

        return Ok();
    }
}

当我使用这个 javascript 代码时,我的操作调用并且一切正常。

$.ajax({
 url: "/api/attendances/?gigId=" + button.attr("data-gig-id"),
 method: "DELETE"
 })
 .done(function () {
     button
     .removeClass("btn-info")
     .addClass("btn-default")
     .text("Going ?");
      })
 .fail(function () {
      alert("Something is failed!");
});

但是当我使用这段代码时,我的 api 没有调用并且失败回调方法执行。

$.ajax({
 url: "/api/attendances/" + button.attr("data-gig-id"),
 method: "DELETE"
 })
 .done(function () {
   button
   .removeClass("btn-info")
   .addClass("btn-default")
   .text("Going ?");
    })
 .fail(function () {
    alert("Something is failed!");
  });

我很困惑,因为在学习电影中使用了第二种调用方法并且它有效。

你能解释一下这个问题吗?

【问题讨论】:

    标签: jquery asp.net ajax asp.net-mvc asp.net-web-api


    【解决方案1】:

    我找到了解决办法

    问题出在Delete方法的定义中,根据WebApiConfig.cs可接受的路由有这样的模式:api/{controller}/{ id}

    所以输入变量名应该是id而不是gigId

    这是正确的代码:

    [HttpDelete]
    public IHttpActionResult Delete(int id)
    {
       var userId = User.Identity.GetUserId();
       var attendance = _context.Attendances.SingleOrDefault(a => a.GigId == id 
        && a.AttendeeId == userId);
    
     if (attendance == null)
     {
         return NotFound();
     }
    
     _context.Attendances.Remove(attendance);
     _context.SaveChanges();
    
     return Ok();
    }
    

    【讨论】:

      【解决方案2】:

      你应该在你的控制器中为动作添加一个路由

      [Route("attendances/{gigId}")]
      公共 IHttpActionResult 删除(int gigId)
      {
          // 你的代码
      }
      

      【讨论】:

      • 谢谢你瑞克马顿
      猜你喜欢
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多