2

I have a datatable that gets values from a database with on every line on the last column a delete button.

$"<button type='submit'  class='btn btn-danger test' id='{i.id}' onclick='return Delete();'>Delete</button>"

My button gets an id which is the id of the model from that row.

I want to delete the row if I click on the button. But can't figure out how to call the method without my application trying to find the view. (I have no delete view and don't want to make one). I've looked it up but nothing works.

My controller action :

    [Authorize(Roles = "user")]
    [HttpDelete]
    public ActionResult Delete(Guid id)
    {
        if (BLayer.getAllGames().ToList().Exists(x => x.id == id))
        {
            BLayer.DeleteGame(id);
        }

        return new EmptyResult();
    }

My Jquery function :

function Delete() {
    var table = $("#tableOverviewGames").DataTable();
    $('#tableOverviewGames tbody').on('click', 'button', function () {
        var idGame = $(this).attr('id');
        $.ajax({
            url: "Delete",
            type: 'DELETE',
            data: { id: idGame },
            async: false,
            contentType: false,
            success: function (data) {
                alert("Vous avez supprimé le jeu");
            },
            error: function (data) {
                console.log(data);
            }
        });
    });

}

Can someone help me please?

Thanks!

EDIT:

This is the error I get in the console :

DELETE http://localhost:3673/Game/Delete 404 (Not Found)
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Jeremy
  • 167
  • 11
  • Suggest you get it working with `[HttpPost]` and `type:'POST'` first, then you can change to use the correct verb. – freedomn-m Mar 04 '19 at 11:03
  • What's the actual value for `{i.id}` / `$(this).attr('id')` - if it can't match the parameter, then it will fail – freedomn-m Mar 04 '19 at 11:04
  • @freedomn-m I made it work with the post but not with the delete. Not sure what's causing the problem. The value from i.id is a Guid but I guess it's treated as a string in jquery – Jeremy Mar 04 '19 at 11:30

2 Answers2

3

Why dont you just return a JSON from the controller such as

return Json(new {success = true})

and then you can (if you need to) do checks in the ajax success against whether or not it worked

JamesS
  • 2,167
  • 1
  • 11
  • 29
  • I still get following error ´DELETE http://localhost:3673/Game/Delete 404 (Not Found)´ – Jeremy Mar 04 '19 at 10:22
  • 1
    @Jeremy Replace `HttpDelete` with `HttpPost`. Change your type to 'POST'. Change `contentType:'Application/json'`. Remove this line `async: false` and finally it's probably best to use `@Url.Action("Delete", "//TheController")` in this case as 'Delete' is a pretty common function name – JamesS Mar 04 '19 at 10:25
  • I changed the things and put a breakpoint on my controller action but it seems like it doesn't get to the controller and I get following error : `jquery-3.3.1.js:9600 POST http://localhost:3673/Game/Delete 500 (Internal Server Error)`. Any idea what it could be? – Jeremy Mar 04 '19 at 10:38
  • @Jeremy If you are using Google Chrome, what is the network section of Dev tools saying – JamesS Mar 04 '19 at 10:42
  • It is calling the action Delete. `Request URL: http://localhost:3673/Game/Delete Request Method: POST Status Code: 500 Internal Server Error Remote Address: [::1]:3673 Referrer Policy: no-referrer-when-downgrade` and `id=18c9224c-c08e-44ab-b4c0-0cec70272ea2`. Is my problem not that I have an argument in my controller Delete(Guid id) action? – Jeremy Mar 04 '19 at 10:49
  • I found this info to : `The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Guid' for method 'System.Web.Mvc.ActionResult Delete(System.Guid)' in 'PSR09554.Web.Controllers.GameController'.` – Jeremy Mar 04 '19 at 10:51
  • Try reading Id as string and then in your controller method try to parse the guid. Also make [HttpDelete("{id}")] – Ram Kumaran Mar 04 '19 at 10:53
  • 1
    @Jeremy Yeah sorry I didnt see that. If you Either stringify the ID and change the parameter to a string in the controller method OR create a json such as this `var json = '{id: "' + idGame + '"}'` and then pass that as the data in the ajax call, you should reach the controller – JamesS Mar 04 '19 at 10:54
  • I made it work by changing the Guid parameter in my controller to string and parse it in the controller itself to guid. And changed my url to : `url: '@Url.Action("Delete", "Game")?Id='+idGame+'',` – Jeremy Mar 04 '19 at 11:18
1

I see that when you make the call you're passing wrong Uri, thats why you got 404 NOT FOUND.

Change your HttpDelete attribute as

[HttpDelete("{id}")]

pass the guid as part of Uri like http://localhost:3673/Game/eef63296-6bb3-40a5-aa89-be69e75a66eb, also any body passed for delete calls will be ignored unless Content-Length header is added, check this link.

If you still insist on a body, try changing signature as shown below

[Authorize(Roles = "user")]
[HttpPost("delete")] //Added route to differentiate Create/Insert REST end point
public ActionResult Delete([FromBody]Guid id)

Your AJAX call should be like

$.ajax({
 url: "Delete",
 type: 'DELETE',
 data: idGame, // Pass value directly.
 sync: false,
 contentType: false,
 success: function (data) {
 alert("Vous avez supprimé le jeu");
},

If I were you, I'd start testing with basic type like string for fields that cause trouble.

Ram Kumaran
  • 621
  • 6
  • 12