简体   繁体   中英

AJAX DELETE request in asp.net MVC

I've always thought that a delete request should be done using type: "DELETE". However, it seems not work in .NET

$.ajax({
    type: "GET",
    url: '/TestController/DeleteTest?id=10',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        if (data) {
            // Works
        }
    },
    error: function (erro) {
        console.debug(erro);
    }
});

Controller:

[HttpGet]
    public JsonResult DeleteTest()
    {
        int id= Int32.Parse(Request["id"]);

        var myTableTest= db.myTable.Where(x => x.id== id).FirstOrDefault();
        db.mytable.Remove(myTableTest);

        db.SaveChanges();
        return Json(true, JsonRequestBehavior.AllowGet);
    }

This code works fine! But if I change to type: "DELETE", it won't work anymore. So, does asp.net have HttpDelete?

Thanks

Your method is decorated with the [HttpGet] attribute. This tells the framework that the method should only be considered if the GET verb is used.

If you want it to respond to DELETE you need to change the attribute to [HttpDelete] instead:

[HttpDelete]
public JsonResult DeleteTest()
{
    ...
}

You should be able to just decorate your action with the [HttpDelete] attribute instead of [HttpGet] . I would also have it set to return an ActionResult instead of JsonResult and return new HttpStatusCodeResult(200) on success in order to make sure your ajax call properly understands the returned result.

In asp.net-mvc we have HttpGet and HttpPost and in this particular case you should be using HttpPost not HttpGet , otherwise anybody can hit the url with query string to request deletion of any record, and another thing is to not use magic strings for generating urls instead of that use Url.Action method which would take care to generate the correct urls for you.

Change your jquery ajax call to use post:

$.ajax({
    type: "POST",
    url: '@Url.Action("DeleteTest","Test")',
    data: {id:10},
    contentType: 'application/json; charset=utf-8',
    success: function (data) {

and then in your action use HttpPost and add parameter to your action method signatures like:

[HttpPost]
public JsonResult DeleteTest(int id)
{

    var myTableTest= db.myTable.Where(x => x.id== id).FirstOrDefault();
    db.mytable.Remove(myTableTest);

    db.SaveChanges();
    return Json(true, JsonRequestBehavior.AllowGet);
}

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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