即使在服务器端代码(Web-api)成功之后,.ajax()调用总是执行.fail()

时间:2016-08-08 05:45:32

标签: ajax asp.net-mvc asp.net-web-api .post ajax-request

我有一个关于web-api页面的ajax调用( / api / attendances )。 它插入一条记录,并返回OK()作为结果。

问题: 插入正确完成,将返回OK,但不是.done()/ success()函数,而是调用.Fail()/错误()。

  

我尝试了两种方式($ .ajax()和$ .Post()),两者都结束了   结果相同

1)

  $.post("/api/attendances", { gid: button.attr("data-gid") })
          .done(function () {
               alert("success...");
              })
          .fail(function () {
              alert("Something failed...");
              });

ServerSide代码:

2)

 public class AttendancesController : ApiController
  {

    //.........other initialize , ... codes in controller

   [HttpPost]
    public IHttpActionResult Attend(AttendDto dto)
    {
        //.....check for duplicate , ...

        var attendanceModel = new Attendance
        {
            AttendeeId = userId,
            gId = dto.gId
        };
        _context.Attendances.Add(attendanceModel);
        _context.SaveChanges();
        return Ok();
    }
}

第3)      定义DTO

  public class AttendDto
    {
        public int  gId { get; set; }
    }

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为它在SaveChanges方法上抛出错误。您可以通过注释Save调用进行验证,然后检查api是否进入失败函数。

相关问题