繁体   English   中英

如何使用Ajax和ASP.NET MVC删除?

[英]How to delete with ajax and ASP.NET MVC?

我正在尝试使用Ajax向ASP.NET MVC 5框架发送删除请求。 只有一页带有一个红色按钮。

在CustomersController中:

[HttpDelete]
[Route("^/customers/delete/{id:int}")]
public ActionResult Delete(int id)
{
   CarDealerContext ctx = new CarDealerContext();
   // Delete customer with given id...
   // If I get a get a breakpoint in here I will be a happy camper!
   return View();
}

在RouteConfig中:

  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  routes.MapMvcAttributeRoutes();

在视图中,我只有:

<input id="deleteBtn" class="btn btn-danger" type="button" 
    value="Delete" data-id="1"/>

这是单击deleteBtn时使用的脚本:

// The script is loaded after Bootstrap and jQuery.

 $("#deleteBtn").on("click", function (event) {
     event.preventDefault();
     var id = $("#deleteBtn").attr("data-id");
     $.ajax({
        url: "/customers/delete/" + id,
        type: 'delete',
        data: { id: id }
     });
 })
 // The request sends http://localhost:61402/customers/delete/1
 // and the response is 404...

我要激活的是在CustomerController中激活Delete方法。 我已经尝试了Route(regex)属性中的几乎所有内容。 第二个我将Method更改为[HttpGet],它可以工作。 也将不胜感激关于这个问题的学习资料。

您需要在IIS中启用这些动词(输入,删除)

Iisexpress可能需要编辑配置文件

更改您的操作方法,如下所示:

[HttpGet]
public ActionResult Delete(int id)
{
    //Your Code
}

需要注意两点:

1)应该设置HTTPGet注释,而不是HTTPDelete,因为从视图发送的请求是GET请求,而不是通常理解为删除操作类型的请求。

2)在您的情况下,这可能不是必需的,但我想我还是会提到它。 ASP.NET MVC更喜欢约定而不是配置。 您无需显式设置该路由。 RouteConfig文件中的默认路由将指向您的方法。

这将是RouteConfig文件中的默认配置:

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = request to this Action Method (if you don't have it, it's probably a good idea UrlParameter.Optional }
            );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM