C# 如何在MVC中删除多个列表项?

C# 如何在MVC中删除多个列表项?,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我想先用EF数据库制作一个MVC4应用程序,这是我两天前自学的。 我面临的问题是,我有一个客户列表,其中有一个属性“IsDeleted”,其值为true或false 基本上,我希望通过单击链接或按钮,同时删除其属性被标记为true的所有客户 到目前为止,我已经尝试过这样做,但似乎我对这一切的工作原理仍有点模糊: 在我的CustomerController中,我添加了以下代码: public ActionResult DeleteAll() { List&l

我想先用EF数据库制作一个MVC4应用程序,这是我两天前自学的。 我面临的问题是,我有一个客户列表,其中有一个属性“IsDeleted”,其值为true或false

基本上,我希望通过单击链接或按钮,同时删除其属性被标记为true的所有客户

到目前为止,我已经尝试过这样做,但似乎我对这一切的工作原理仍有点模糊:

在我的CustomerController中,我添加了以下代码:

        public ActionResult DeleteAll()
    {
        List<Customer> cusList = new List<Customer>();
        IEnumerable<Customer> customerList = db.Customers.ToList().Where(i => i.IsDeleted == true);
        foreach (var Item in customerList) { cusList.Add(Item); }
        return View(customerList);
    }

    [HttpPost, ActionName("DeleteAll")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteAllConfirmed()
    {
        List<Customer> cusList = new List<Customer>();
        IEnumerable<Customer> customerList = db.Customers.ToList().Where(i => i.IsDeleted == true);
        foreach (var Item in customerList) { cusList.Add(Item); }
        foreach (var item in cusList) { db.Customers.Remove(item); }
        return RedirectToAction("Index");
    }
public ActionResult DeleteAll()
{
List cusList=新列表();
IEnumerable customerList=db.Customers.ToList(),其中(i=>i.IsDeleted==true);
foreach(customerList中的var项){cusList.Add(项);}
返回视图(customerList);
}
[HttpPost,ActionName(“DeleteAll”)]
[ValidateAntiForgeryToken]
公共行动结果删除所有已确认()
{
List cusList=新列表();
IEnumerable customerList=db.Customers.ToList(),其中(i=>i.IsDeleted==true);
foreach(customerList中的var项){cusList.Add(项);}
foreach(cusList中的var项){db.Customers.Remove(项);}
返回操作(“索引”);
}
所以我有点不确定下一步该去哪里,甚至不确定这是否是一种可行的方法。 如果可行,如何在视图中调用此操作

任何想法都将不胜感激


最好的祝愿,

您的post方法中有一些冗余代码。您正在查询数据库并获得所需的结果。这些实体依次被抛出到一个列表中,然后您对它们进行迭代以删除它们。此外,您忘了告诉上下文保存更改。通过缩短以下步骤,您可以节省一些时间、内存和cpu周期:

[HttpPost, ActionName("DeleteAll")]
[ValidateAntiForgeryToken]
public ActionResult DeleteAllConfirmed()
{
    IEnumerable<Customer> customerList = db.Customers.Where(i => i.IsDeleted == true);
    //Now you have everything you need.
    foreach (var Item in customerList) 
    { 
        //Remove
        db.Customers.Remove(Item); 
    }
    //and save. done
    db.SaveChanges(); //important!
    return RedirectToAction("Index");
}
如果您愿意,可以将其缩减为一行:

public ActionResult DeleteAll()
{
    return View(db.Customers.Where(i => i.IsDeleted == true));
}

我还是有点不确定,你说的如何在视图中调用它是什么意思。

非常感谢你这么快的回答,当我问如何调用它时,我的意思是我想有一个视图来列出所有标记为“真”的要删除的项目,然后我会在该视图中单击一个按钮或一个actionlink,它将被全部删除。我希望它更清楚?这是很基本的。右键单击
DeleteAll()
方法,然后单击生成视图。选择一个列表模板。在此视图中,您可以创建一个按钮,该按钮调用
deleteAllconfirm()
POST方法,您就完成了。我建议你通过在的官方教程学习基础知识。我已经成功地做到了,之前的一次输入错误让我认为我的代码是错误的,再次感谢你的帮助:)不客气。如果我的回答确实对你有帮助,请考虑提高投票率,或将其标记为回答谢谢,我曾试图提高投票率,但我需要15%的声誉才能做到这一点。我把它标记为答案!
public ActionResult DeleteAll()
{
    return View(db.Customers.Where(i => i.IsDeleted == true));
}