Delete record by using ajax from database EntityFramework

asp.net-ajax asp.net-mvc-3 entity-framework-6 javascript jquery

Question

I'm a novice attempting to remove the entry from the database usingJavaScript , Ajax and Json in 14-zzz-zzzz. My delete button, however, does not function effectively.

My action code in the controller class 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 here is my JavaScript code:

<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")
        });

If someone can assist me, I would be quite grateful.

1
1
6/20/2018 6:38:01 PM

Accepted Answer

Your model id must be included to the jquery data tag:

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

Afterward, 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")
        });
2
6/20/2018 11:21:29 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow