How can I delete data from my database in ASP.NET MVC without reloading the page ?
I tried all the methods but couldn't find a solution.
This is my ajax code :
(".remove-hasan").on("click", function () {
var id = $(this).attr("data-id");
$.ajax({
url: "/Main/DeleteFavourite" id,
type: "POST",
data: { id: id, },
success: function (response) {
if (response == "ok") {
$(".modal-action-messages").empty();
$(".modal-action-messages").append("Ürün Başarıyla Favorilerinizden Çıkarılmıştır.");
$this.find(".remove").removeClass(".remove");
$this.find(".remove").addClass(".remove");
}
}
});
});
Controller :
[HttpPost]
public IActionResult DeleteFavourite(int id)
{
var product = _uow.Favourite.GetAll()
.Where(p => p.ProductId == id)
.FirstOrDefault();
_uow.Favourite.Delete(product);
return Json("ok");
}
CodePudding user response:
So, your major problem is how to remove the entry from frontend i.e. HTML page.
Once you get the success from ajax call, you need to find that row from HTML table and simply delete it.
Assuming, you code is already reaching inside
response == "ok"
It's always suggested to use Id for each row, which I think you already have.
success: function (response) {
if (response == "ok") {
$('[data-id=' id ']').remove();
}
}
Here data-id is used inside jQuery selector to uniquely find that row.
CodePudding user response:
As I see your HTML file. You can do it in the following way.
Steps
- In the
success
function. find the closesttr
and then call jQuery functionremove()
$(".remove-hasan").on("click", function () {
var delButton = $(this);
var id = $(this).attr("data-id");
$.ajax({
url: "/Main/DeleteFavourite" id,
type: "POST",
data: { id: id, },
success: function (response) {
if (response == "ok") {
//Your code
...
delButton.closest("tr").remove();
}
});
});