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");
}
3
Answers
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.
Sending an AF token with the post request or removing the [ValidateAntiforgeryToken] attribute should work.
You can also try to add AntiForgoryToken into ajax header. Here is a demo:
js: