视图页:
<table>
<tr>
<td><input type="checkbox" id="one"><button id="remove">一键删除</button></td>
</tr>
</table>
<tbody>
@foreach (var item in Model)
{
<tr>
<td><input type="checkbox" value="@Html.DisplayFor(modelItem => item.ID)" />
</td>
</tr>
}
</tbody>
</table>
JS:
<script>
///全选框
$("#one").click(function () {
$(":input:checkbox:gt(0)").prop("checked", $(this).prop("checked"))
});
$("#remove").click(function () {
var ids = new Array();//创建一个数组
$("input:checkbox:gt(0):checked").each(function () {
var id = $(this).val();
ids += id + ',';
});
console.log(ids)
var msg = "确定要删除吗?"
if (confirm(msg) == true) {
//异步访问批量删除方法, 把数组传入controller层
$.ajax({
type: "post",
url: "/Product/Remove",
data: { ids: ids },
success: function (data) {
if (data.state == 10000) {
alert("删除成功!");
location.reload();
}
else {
alert("删除失败!");
}
}
});
}
else { return false }
});
</script>
controller:
public JsonResult Remove(string ids)
{
ids = ids.Substring(0, ids.Length - 1); //删除字符串最后一个字符
string[] datalist = ids.Split(',');
foreach (var item in datalist)
{
int daa=int.Parse(item);
var da = db.Product.FirstOrDefault(c => c.ID == daa);
db.Product.Remove(da);
}
db.SaveChanges();
return Json(new { state = "10000" });
}