Asp.net MVC 批量删除数据

时间:2021-07-28 09:12:16

ProductList视图

<div class="mid">
<div id="editInfo">
@using (Html.BeginForm("Delete", "Admin"))
{
<div class="c1 headFont">
<input type="checkbox" id="ckbSelAll" onclick="SelectAll(this.checked)" />
<input type="submit"value="多选删除" onclick="return confirm('确定要删除吗?')" />
</div>
<div class="c3 headFont">产品名称</div>
<div class="c4 headFont">发布时间</div>
<div class="c5 headFont">编辑</div>
<ul id="info">
@foreach (var p in Model)
{
<li>
<div class="c1 list">@Html.CheckBox("checkitem", new {value=p.ID })
@Html.ActionLink("删除", "Delete", new { id = p.ID }, new { onclick = "return confirm('确定删除吗?')" })
</div>
<div class="c3 list">@Html.DisplayFor(modelItem => p.productName)</div>
<div class="c4 list">@Html.DisplayFor(modelItem => p.inDate,"LongDateTime")</div>
<div class="c5 list">@Html.ActionLink("编辑", "EditProduct", new { id=p.ID })</div>
</li>
}
</ul>
}
</div>
</div>

效果图如下:

Asp.net MVC 批量删除数据

Controller代码:

public ActionResult Delete(int id)
{
ProductInfo pro = db.ProductInfoes.Find(id);
db.ProductInfoes.Remove(pro);
db.SaveChanges();
return RedirectToAction("ProductList");
}
[HttpPost]
public ActionResult Delete(FormCollection collection)
{
string str = collection["checkitem"];// checkitem复选框的名
string[] strDelete = str.Split(',');
foreach (var i in strDelete)
{
if (i != "false")
{
ProductInfo pro = db.ProductInfoes.Find(int.Parse(i));
db.ProductInfoes.Remove(pro);
db.SaveChanges();
}
}
return RedirectToAction("ProductList");
}