Mark Tabor

Mark Tabor

  • 569
  • 1.9k
  • 430.8k

Delete using Ajax Call in .NET MVC

Oct 25 2019 2:14 AM
I am calling Delete controller method from ajax on button click but when i click the button it gives error like "Object reference not set to an instance of an object."
 
I have write a code for the ajax and calling delete method previously the javascript code get called on every page load rather than on button click but then i add e.preventDefault(); The issue is now it is giving error rather then moving to the controller delete method.
 
My Javascript code
  1. <script> function DeleteCall(id) { // $(document.getElementById("sbmtInput").click(function(e){} $('btnDelete').click(function (e) { e.preventDefault(); $.ajax({ type: "POST", url: '@Url.Action("Delete", "Student_Experience")', data: JSON.stringify({ id: id }), //use id here dataType: "json", contentType: "application/json; charset=utf-8", success: function () { // alert("Data has been deleted."); location.reload(); $(".demo1").html(result); }, error: function () { alert("Error while deleting data"); } }); }); </script>  
  1. [httppost]  
  2. public ActionResult Delete(int? id) { if (id == null)  
  3. return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } S  
  4. tudent_Experience student_Experience = db.Student_Experience.Find(id);  
  5. if (student_Experience == null) { return HttpNotFound(); }  
  6. // Student_Experience student_Experience = db.Student_Experience.Find(id);  
  7. db.Student_Experience.Remove(student_Experience);  
  8. db.SaveChanges(); return RedirectToAction("Create","Students"); // return View(student_Experience); }

Answers (4)