MVC3 中的 jQuery Ajax POST

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

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

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

类别 Controller 中的操作:

[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?

最佳答案

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

$.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');
    }
});

关于MVC3 中的 jQuery Ajax POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13377139/

相关文章:

php - 点击链接后 JQuery 提交表单

jquery - 使用 Apache 代理发布到 HTTPS 端点时出错

javascript - 如何从异步调用返回响应?

javascript - jQuery .ajax() - 向 POST 请求添加查询参数?

asp.net-mvc-3 - 我的模型应该如何将动态添加的文本框的数据存储在数据库中?

javascript - jQuery:如何检查以确保所有异步操作已完成

ajax - 如何通过laravel中的ajax调用发送csrf token ?

asp.net-mvc-3 - ASP.NET MVC 3 : How to get User's Role in a Controller Method?

jquery - 如何在 jquery-ui 自动完成中映射数据不起作用

php - jQuery 中的空格破坏了 img src