MVC3中的jQuery Ajax POST

时间:2012-11-14 10:35:03

标签: jquery ajax asp.net-mvc-3 post

当我使用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');
      }
    });
  });
});

为什么click事件不会生成POST?

1 个答案:

答案 0 :(得分:5)

您需要通过设置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');
    }
});