我是新手,正在尝试使用 MVC实体框架中的JavaScript
,Ajax
和Json
从数据库中删除记录。但是我的删除按钮无法正常工作。
在控制器类中,我的动作代码是
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);
}
我的JavaScript代码是
<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")
});
如果有人帮助我,我将非常感激。
答案 0 :(得分:2)
您需要在jquery数据标签中添加模型ID:
<button id='deleteRecord' data-model-id="@model.Id">delete</button>
然后使用javascript代码:
$("#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")
});
答案 1 :(得分:1)
我认为该错误来自您的ajax调用的type属性。您为此属性分配“删除”,但它必须为“ 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);
}
});
并且控制器中的操作方法必须用[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);
}
答案 2 :(得分:1)
经过很多时间,我能够解决我的问题。
现在我的javaScript代码
<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);
}
答案 3 :(得分:0)
您应该尝试通过更改:
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
StudentId: stdId
}
收件人:
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
'id':stdId
}