0

I am beginner and trying to delete the record from database by using JavaScript, Ajax and Json in MVC Entity Framework. But my delete button is not working well.

In controller class my action code is

public ActionResult Delete(int id) {
            using (StudentContext db = new StudentContext()) {
                Student std = db.Student.Where(x => x.Id == id).FirstOrDefault<Student>();
                db.Student.Remove(std);
                db.SaveChanges();
              }
              return Json(true, JsonRequestBehavior.AllowGet);
        }

and my JavaScript code is

<button id='deleteRecord'>delete</button>

$("#deleteRecord").click(function () {
                var StudentId = $(this).val();
                var stdId = parseInt(StudentId);
                $.ajax({
                    url: "/AjaxStudent/Delete",
                    type: 'Delete',
                    data: {
                        StudentId: stdId
                    }
                }).done(function () {
                    alert("Deleted")
                });
            });

        }).error(function () {
            alert("Failed")
        });

I shall be very thankful if anybody help me.

2
  • Do you get any errors, or is it just inconsistent when you try to delete? Are there any constraints or related records that you are not considering? ie. Are you trying to delete a student id where this is being used in a different table? Commented Jun 20, 2018 at 18:47
  • @fdsafdsafdsafdsafs Oh yes, I am getting this error System.ArgumentException: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Delete(Int32)' in 'AjaxStudentCall.Controllers.AjaxStudentController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters and my student Id is in one table. Commented Jun 20, 2018 at 19:13

4 Answers 4

1

You need to add your model id in jquery data tag:

<button id='deleteRecord' data-model-id="@model.Id">delete</button>

Then in javascript code:

$("#deleteRecord").click(function () {
                var StudentId = $(this).data("model-id");
                var url = "/AjaxStudent/Delete/" + StudentId;
                $.ajax({
                    url: url,
                    type: 'Delete',
                }).done(function () {
                    alert("Deleted")
                });
            });
        }).error(function () {
            alert("Failed")
        });
Sign up to request clarification or add additional context in comments.

5 Comments

My answer does not help you? Now what is the error?
In button tag this code data-model-id="@model.Id" is not working.
data-model-id should contains model's id (record id or primary key) that you want to delete: for example, if you want to delete model with id=7 the data-model-id="7". You are free to change @model.id
the error you are getting: "System.ArgumentException: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'..." is because delete action in AjaxStudentController does not receive the id parameter.
just see my below answer. Thank you I got it with help of your concept.
1

I think that the error comes from the type attribute of your ajax call. You assign "delete" to this attribute, but it must be "POST":

 $.ajax({
          url: "@Url.Action("Delete","AjaxStudent")",
          type: "POST", // here is your problem,
          data: { StudentId: stdId },
          dataType: 'json',
          success: function() {                 
                alert("Deleted");
            },
          error: function(dat) {
                alert(data.x);
            }
        });

And the action method in your controller must be decorated with [httppost] :

 [HttpPost]
 public JsonResult Delete(int StudentId) 
 {
    using (StudentContext db = new StudentContext()) 
    {
        Student std = db.Student.Where(x => x.Id == StudentId).FirstOrDefault<Student>();
        db.Student.Remove(std);
        db.SaveChanges();
      }
      return Json(true, JsonRequestBehavior.AllowGet);
  }

1 Comment

Yes, Little bit I am agree with you but using type :"Post" , just see my below answer.
0

you should try by changing :

 $.ajax({
                url: "/AjaxStudent/Delete",
                type: 'Delete',
                data: {
                    StudentId: stdId
                }

to:

 $.ajax({
            url: "/AjaxStudent/Delete",
            type: 'Delete',
            data: {
                'id':stdId
            }

Comments

0

After lots of time I am able to resolve my problem.

Now my javaScript code

<button class='deleteRecord' data-stid=" + students[i].Id + " >delete</button> 
$(".deleteRecord").click(function () {
                var StudentId1 = $(this).data("stid");
                debugger;
                $.ajax({
                    url: "/AjaxStudent/Delete/" + StudentId1,
                    type: "Post"
                }).done(function () {

                    getAllStudents();

                    });
                });
            });

Controller.cs

public ActionResult Delete(int id) {
            using (StudentContext db = new StudentContext()) {
                Student std = db.Student.Where(x => x.Id == id).FirstOrDefault();
                db.Student.Remove(std);
                db.SaveChanges();
            }

            return Json(true, JsonRequestBehavior.AllowGet);
        }

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.