1

当我使用 jQuery.ajax 和 POST 方法从数据库中删除一个项目时,我收到此错误:

GET Http://localhost:54010/Admin/Category/Delete?id=77 404 Not Found

CategoryController 中的操作:

[HttpPost]
public ActionResult Delete(int id) {
  try {
    db.CategoryRepository.Delete(id);
    db.Save();
    return Json(new {Result = "OK"});
  } catch (Exception ex) {
    return Json(new { Result = "ERROR", Message = ex.Message });
  }
}

看法:

<a id="delete-category" class="btn btn-small" href="#">
  <i class="icon-remove"></i>
  @Resource.delete
</a>

JavaScript:

$(function () {
  $('#delete-category').click(function (event) {
    event.preventDefault();
    $.ajax({
      method: 'POST',
      url: '@Url.Action("Delete","Category")',
      dataType: 'json',
      data: { id: '@Model.CategoryModel.Id' },
      success: function (data, textStatus, jqXHR) {
        console.log("success");
      },
      error: function () {
        alert('error');
      }
    });
  });
});

为什么点击事件不生成POST?

4

1 回答 1

7

您需要通过设置参数告诉ajax()方法发出post请求:type

$.ajax({
    // method: 'POST', <-- remove this
    type: 'POST', // <-- add this
    url: '@Url.Action("Delete","Category")',
    dataType: 'json',
    data: { id: '@Model.CategoryModel.Id' },
    success: function (data, textStatus, jqXHR) {
        console.log("success");
    },
    error: function () {
        alert('error');
    }
});
于 2012-11-14T10:37:43.090 回答