Home > database >  ASP.NET Core 6.0 - Delete from database with jQuery.ajax results in POST HTTP 400 ERROR
ASP.NET Core 6.0 - Delete from database with jQuery.ajax results in POST HTTP 400 ERROR

Time:12-24

I started learning ASP.NET Core 6.0 a week ago. I've made a real-time chat with SignalR, I'm also saving the messages to my database.

As for now, it's just a table, each row contains in separate columns the username, message, and a delete button. I'm appending the new rows as new messages come.

The problem is that my delete button doesn't works.

In the console I'm getting a: POST https://localhost:7122/Chat/DeleteMessage/1 400 error message.

The button:

 <input type="button" onclick="Delete(@obj.Id)" value="Delete"/>

The script:

<script>
function Delete(id) {
$.ajax({
     url: "/Chat/DeleteMessage/"   id,
      type: "POST",
  })
}
</script>

And the controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult DeleteMessage(int id)
    {
        db.Chat.Remove(db.Chat.Find(id));
        db.SaveChanges();
        return RedirectToAction("Index");
    }

CodePudding user response:

It's soo dumb but the problem was the [ValidateAntiForgeryToken]. I've just noticed the error in the Debug output so I removed it and now it works just fine.

CodePudding user response:

Sending an AF token with the post request or removing the [ValidateAntiforgeryToken] attribute should work.

  • Related