HelpNeeded HelpNeeded - 1 month ago 5
Ajax Question

Removing row from table

Good Afternoon, I would like to remove a row from a table , in which when I click on the delete button the whole row would be deleted , the data that should be deleted are Name , Contact number and Age which are also saved in the database so what I would like to achieve is that when the delete button is clicked the data on the website and database will be cleared .Thank you .

I had tried this method , but it only deletes the row on the website and whenever I reload the page , the data will appear again

$('.btnDelete').on('click', function() {
$(this).closest('tr').remove();
return false;
});


<td>
<button href="javascript:void(0);" id="btnDelete" class="btnDelete">Delete</button>
</td>

Answer

You have to write delete functionality in controller like this

public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    table1 tableobject = db.table1.Find(id);
    if (tableobject == null)
    {
        return HttpNotFound();
    }
    return View(tableobject );
}


[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    table1 tableobject = db.table1.Find(id);
    db.table1.Remove(tableobject);
    db.SaveChanges();
    return RedirectToAction("Index");
}

in view

 $('.btnDelete').on('click', function() {

     $.ajax({
        type: "post",
        url: "@Url.Action("Delete","ControllerName")",
        ajaxasync: true,
        data: { id : $(this).find('td').eq(0).text()  },
        success: function () {

            alert("success");
              $(this).closest('tr').remove();
            // Perform redirect

        },
        error: function (data) {
            alert(data.x);
        }
    });
});
Comments