ajax删除DB数据

时间:2021-05-26 06:56:16

1.前台js

 $().ready(function () {

     $('[name="checkAll"]').click(function () {
if ("checked" == $('input[name="checkAll"]').attr("checked")) {
$('input[type="checkbox"]').attr("checked", "checked");
} else {
$('input[type="checkbox"]').removeAttr("checked");
}
}); $('input[name="btnDelete"]').click(function () {
var checkCount = 0; $('input[type="checkbox"]').not('input[name="checkAll"]').each(function (index, element) {
if ("checked" == $(this).attr("checked")) {
checkCount++;
}
}); if (checkCount <= 0) {
alert("请选择您要删除的数据!");
return false;
} if (confirm("确定要删除吗?")) {
var data = "["; $('input[type="checkbox"]').not('input[name="checkAll"]').each(function (index, element) {
if ("checked" == $(this).attr("checked")) {
data += "{id : " + $(this).val() + "} ,";
}
}); if (data != "[") {
data = data.substring(0, data.length - 1) + "]"; $.post("/User/DeleteById", data, function success(result) {
//1.ajax返回单个字符串内容
//var msg = " <font style='color:red'>" + result + "</font>";
//if ($('#ajaxMsg').html() == '') {
// $('#ajaxMsg').append(msg);
//} //2.ajax返回多个字符串内容
var msg = " <font style='color:red'>删除成功!</font>";
if ($('#ajaxMsg').html() == '') {
$('#ajaxMsg').append(msg);
} $('input[name="checkAll"]').removeAttr("checked"); $('input[type="checkbox"]').not('input[name="checkAll"]').each(function (index, element) {
$(this).parent().parent().remove();
}); var ajaxResult = $.parseJSON(result);
$.each(ajaxResult, function (index, element) {
var tr = "<tr>"
+ "<td><input type='checkbox' value='" + element.ID + "' /></td>"
+ "<td><a href='/User/Detail/" + element.ID + "'>" + element.UserName + "</a></td>"
+ "<td>" + element.Phone + "</td>"
+ "<td>" + element.Email + "</td>"
+ "<td>" + element.Address + "</td>"
+ "<td>" + element.CreateTime + "</td>"
+ "<td>" + element.UpdateTime + "</td>"
+ "<td><a href='/User/Edit/" + element.ID + "'>修改</a></td>"
+ "<td><a href='/User/Delete/" + element.ID + "'>删除</a></td>"
+ "</tr>";
$('table').append(tr);
});
});
}
}
});
});

2.后台代码:

[HttpPost]
public ActionResult DeleteById()
{
String ajaxId = Request.Params[]; JavaScriptSerializer js = new JavaScriptSerializer();
List<AjaxReq> ajaxReqList = js.Deserialize<List<AjaxReq>>(ajaxId);
if (null != ajaxReqList && < ajaxReqList.Count())
{
foreach (AjaxReq ajaxReq in ajaxReqList)
{
UserDto user = new UserDto();
user.ID = ajaxReq.ID;
db.Entry<UserDto>(user).State = System.Data.EntityState.Deleted;
db.SaveChanges();
}
} List<UserDto> userList = db.Users.ToList(); //1.ajax返回单个字符串内容
//return base.Json("删除成功!"); //2.ajax返回多个字符串内容
return base.Json(js.Serialize(userList)); }