I am doing this project in mvc .net and i cant get the delete button to work for some reason. Basically clicking on it does nothing. I want to delete an item from the database. Can someone help me fix this?
Here is the delete in my controller:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
Medicines medicines = db.Medicines.Find(id);
db.Medicines.Remove(medicines);
db.SaveChanges();
return RedirectToAction("CreateNewMedicine");
}
Here is my button in the index view:
@foreach (var item in Model)
{
<td>
<button medicine-Id="@item.Id" >Delete</button>
</td>
</tr>
}
Here is my function script in the index view:
@section scripts{
<script>
$(document).ready(function () {
var table = $("#tableid").DataTable();
$("#tableid .js-delete").on("click", function () {
var button = $(this);
bootbox.confirm("Are you sure?", function (result) {
if (result) {
$.ajax({
url: "C:\Users\User\Desktop\it&david\OnlinePharmacy2\OnlinePharmacy2\Views\Medicines\Delete.cshtml" button.attr("medicine-Id"),
method: "GET",
success: function () {
table.row(button.parents("tr")).remove().draw();
},
error: function (err) {
console.log(err);
}
});
}
})
}
})
</script>
}
CodePudding user response:
You should change Method GET To POST in the ajax query like code below :
method: "POST",
Because the action header is "HttpPost" type.
CodePudding user response:
Here are the some necessary actions you perform.
Controller
[HttpPost]
public ActionResult Delete(int id)
{
Medicines medicines = db.Medicines.Find(id);
db.Medicines.Remove(medicines);
db.SaveChanges();
return RedirectToAction("CreateNewMedicine");
}
View
@foreach (var item in Model)
{
<tr>
<td>
<button medicine-Id="@item.Id" data-id="@item.Id" >Delete</button>
</td>
</tr>
}
script
$(document).ready(function () {
var table = $("#tableid").DataTable();
$("#tableid .js-delete").on("click", function () {
var button = $(this);
var _id = $(this).attr("data-id");
bootbox.confirm("Are you sure?", function (result) {
if (result) {
$.ajax({
url: "/ControllerName/Delete?id=" _id,
type: "POST",
contentType: "application/json; charset=utf-8",
datatype : "json",
success: function () {
table.row(button.parents("tr")).remove().draw();
},
error: function (err) {
console.log(err);
}
});
}
});
}
});
Note: When you decorate your Action Method with the ValidateAntiForgeryToken
attribute. you have to supply the __RequestVerficationToken
to prevent CSRF attacks.