I have several entries on my page and each entry have a delete button and when i click on a button the ajax is not calling the api ?
I am trying to figure out that where i am going to create a mistake. If someone figured out. let me know please.
Button
<button type="button" data-entryId="@entry.Id" class="btn-delete btn btn-danger CustomStyleForEditAndDeleteButton">
Delete
</button>
Api
// Get : api/entries/1
[HttpDelete]
public IHttpActionResult DeleteEntry(int id)
{
var entryInDb = _context.Entries.SingleOrDefault(x => x.Id == id);
if (entryInDb == null)
return NotFound();
else
_context.Entries.Remove(entryInDb);
_context.SaveChanges();
return Ok();
}
jQuery
@section scripts{
<script>
$(document).ready(function () {
jQuery(".btn-delete").click(function () {
bootbox.confirm({
size: "small",
message: "Are you sure you want to delete this post?",
callback: function (result) {
if (result) {
jQuery.ajax({
url: "/api/entries/" + this.attr("data-entryId"),
method: "DELETE",
success: function () {
bootbox.alert("The post is successfully deleted!");
},
error: function () {
bootbox.alert("something goes wrong when attempting delete operation please try again.");
}
});
}
}
});
});
});
</script>
}
Thanks.
Problem was with jQuery Button. this.attr("//..")
Correct jQuery Code:
$(document).ready(function () {
// #entriesDetails - Parent element of a button.
jQuery("#entriesDetails").on("click", ".btn-delete", function () {
var button = $(this);
bootbox.confirm({
size: "small",
message: "Are you sure you want to delete this post?",
callback: function (result) {
if (result) {
jQuery.ajax({
url: "/api/entries/" + button.attr("data-entryId"),
method: "DELETE",
success: function () {
bootbox.alert("The post is successfully deleted!");
window.location.reload();
},
error: function () {
bootbox.alert("something goes wrong when attempting delete operation please try again.");
window.location.reload();
}
});
}
}
});
});
});