1.前台js
1 $().ready(function () { 2 3 $('[name="checkAll"]').click(function () { 4 if ("checked" == $('input[name="checkAll"]').attr("checked")) { 5 $('input[type="checkbox"]').attr("checked", "checked"); 6 } else { 7 $('input[type="checkbox"]').removeAttr("checked"); 8 } 9 }); 10 11 $('input[name="btnDelete"]').click(function () { 12 var checkCount = 0; 13 14 $('input[type="checkbox"]').not('input[name="checkAll"]').each(function (index, element) { 15 if ("checked" == $(this).attr("checked")) { 16 checkCount++; 17 } 18 }); 19 20 if (checkCount <= 0) { 21 alert("请选择您要删除的数据!"); 22 return false; 23 } 24 25 if (confirm("确定要删除吗?")) { 26 var data = "["; 27 28 $('input[type="checkbox"]').not('input[name="checkAll"]').each(function (index, element) { 29 if ("checked" == $(this).attr("checked")) { 30 data += "{id : " + $(this).val() + "} ,"; 31 } 32 }); 33 34 if (data != "[") { 35 data = data.substring(0, data.length - 1) + "]"; 36 37 $.post("/User/DeleteById", data, function success(result) { 38 //1.ajax返回单个字符串内容 39 //var msg = " <font style='color:red'>" + result + "</font>"; 40 //if ($('#ajaxMsg').html() == '') { 41 // $('#ajaxMsg').append(msg); 42 //} 43 44 //2.ajax返回多个字符串内容 45 var msg = " <font style='color:red'>删除成功!</font>"; 46 if ($('#ajaxMsg').html() == '') { 47 $('#ajaxMsg').append(msg); 48 } 49 50 $('input[name="checkAll"]').removeAttr("checked"); 51 52 $('input[type="checkbox"]').not('input[name="checkAll"]').each(function (index, element) { 53 $(this).parent().parent().remove(); 54 }); 55 56 var ajaxResult = $.parseJSON(result); 57 $.each(ajaxResult, function (index, element) { 58 var tr = "<tr>" 59 + "<td><input type='checkbox' value='" + element.ID + "' /></td>" 60 + "<td><a href='/User/Detail/" + element.ID + "'>" + element.UserName + "</a></td>" 61 + "<td>" + element.Phone + "</td>" 62 + "<td>" + element.Email + "</td>" 63 + "<td>" + element.Address + "</td>" 64 + "<td>" + element.CreateTime + "</td>" 65 + "<td>" + element.UpdateTime + "</td>" 66 + "<td><a href='/User/Edit/" + element.ID + "'>修改</a></td>" 67 + "<td><a href='/User/Delete/" + element.ID + "'>删除</a></td>" 68 + "</tr>"; 69 $('table').append(tr); 70 }); 71 }); 72 } 73 } 74 }); 75 });
2.后台代码:
[HttpPost] public ActionResult DeleteById() { String ajaxId = Request.Params[0]; JavaScriptSerializer js = new JavaScriptSerializer(); List<AjaxReq> ajaxReqList = js.Deserialize<List<AjaxReq>>(ajaxId); if (null != ajaxReqList && 0 < 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)); }