i'm trying to implement a single page application in mvc.net using ajax , i'm facing problem with implementing the delete service , here is my Delete action method :
[HttpPost]
public ActionResult Delete(int id)
{
Movie movie = db.Movies.Find(id);
db.Movies.Remove(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
here is my Delete onclick function :
function Delete(id){
//here i want to take delete the row with it specifc id ,
$.ajax({
type: "POST",
url: '@Url.Action("Delete")',
data: JSON.stringify({ ID: id }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
// alert("Data has been deleted.");
LoadData();
},
error: function () {
alert("Error while deleting data");
}
});
this delete should be called when the delete button is clicked, which is created by the load Data function :
function LoadData() {
$("#tblStudent tbody tr").remove();
$.ajax({
type: 'POST',
url: '@Url.Action("getStudent")',
dataType: 'json',
data: { id: '' },
success: function (data) {
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='prtoducttd' id='MovieID'>" + item.ID + "</td>"
+ "<td class='prtoducttd'>" + item.Name + "</td>"
+ "<td class='prtoducttd'>" + item.Type + "</td>"
+ "<td class='prtoducttd'>" + item.date + "</td>"
+ "<td class='prtoducttd'>" + "<input class='btn btn- primary' name='submitButton' id='btnEdit' value='Edit' onclick='delete' type='button'>"+ "<input class='btn btn- primary' name='submitButton' id='btnDel' value='Delete' type='button'>" + "</td>"
+ "</tr>";
$('#tblStudent tbody').append(rows);
});
},
how to pass the id of the movie to the delete function when the button is clicked ?
idattributes). Get rid ofonclick='delete'and use$('#tblStudent').on('click', '.delete', function() { var id = $(this).data('id'); ...and then change the button to"<button class="delete" data-id=" + item.ID + ">Delete</button>"LoadData()in the delete function. Just remove the associated element from the DOM. There is no point degrading performance by downloading all the data again