1

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 ?

3
  • You have multiple problems including invalid html (duplicate id attributes). Get rid of onclick='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>" Commented Nov 7, 2017 at 9:27
  • And why in the world are you calling 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 Commented Nov 7, 2017 at 9:29
  • i''m just beginner trying to learn ,, thank u very much i think i get your point... @StephenMuecke Commented Nov 7, 2017 at 9:32

2 Answers 2

2

parameters in controller action method and in data : {} of ajax call must be the same, as you are using public ActionResult Delete(int id) in Controller you must use id : id in ajax call.

     $.ajax({
        type: "POST",
        url: '@Url.Action("Delete")',
        data: JSON.stringify({ id: id }), //use id here
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
           // alert("Data has been deleted.");
            LoadData();
        },
        error: function () {
            alert("Error while deleting data");
        }
    });

second thing, it is not a good idea to write whole row in load data function in single var row variable. you can declare var row = ''; before each loop and then can do like this.

var rows = '';
        $.each(data, function (i, item) {
            rows += "<tr>",
            rows += '<td>' + item.MovieID+ '</td>'
            //and so on.............and lastly use .html instead of append

            $('#tblStudent tbody').html(rows);
        });

for reference, refer this link :- http://www.c-sharpcorner.com/article/crud-operation-in-asp-net-mvc-using-ajax-and-bootstrap/

Sign up to request clarification or add additional context in comments.

Comments

0

The ajax needs some modifications. The name of the parameters and method name should exactly match in controller and ajax.

 $.ajax({
            type: "POST",
            url: '/ControllerName/Delete',// same case sensitive action name
            data: JSON.stringify({ id: id }), //small letter id, same as in controller parameter
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function () {
               // alert("Data has been deleted.");
                LoadData();
            },
            error: function () {
                alert("Error while deleting data");
            }

If still the delete action not getting called, remove the json.stringify and just pass 'id': idval in data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.