我有一个对象列表,显示在“结账”屏幕中,如下所示:
因此每一行都被视为一个对象,都是篮子列表的一部分。
用户单击“添加到购物车”,这样,就会使用上面所示的相应信息“产品”、“数量”、“价格”和“总计”来编译列表元素。因此,我现在想要做的就是通过单击相应的“删除”按钮来删除特定的列表元素,并最终从上面的结帐表中删除该对象(行)。
下面是负责将相关信息(从对象收集)添加到购物篮列表中的 ActionResult,也称为“basketList”。
public ActionResult Yacht1()
{
List<Yacht> yachts = GetYachtData();
return View(yachts);
}
[HttpPost]
public ActionResult Yacht1(int yachtQuantity, float yachtPrice, string yachtName)
{
double totalPrice = Convert.ToDouble(yachtQuantity) * Convert.ToDouble(yachtPrice);
Basket basketList = new Basket(yachtQuantity, yachtPrice, yachtName, totalPrice);
HomeController.basketItems.Add(basketList);
return RedirectToAction("Yacht1");
}
public static List<Basket> basketItems = new List<Basket>();
下面是篮子类的控制器。
public class BasketController : Controller
{
// GET: Basket
public ActionResult Basket()
{
var itemList = HomeController.basketItems;
return View(itemList);
}
}
最后是显示这些单独行元素的视图。
<tbody class="customBody">
@foreach (var itemList in Model)
{
<tr class="customRow">
<td class="customData">@itemList.Name</td>
<td class="customData">@itemList.Quantity</td>
<td class="customData">@itemList.Price</td>
<td class="customData">@itemList.Total</td>
<td class="customData"><button class="btn-dark">Delete</button></td>
</tr>
}
</tbody>
首先尝试为每个对象添加身份(ID),该对象将用于更新和删除购物车中的商品。 新班级就像
public class Basket {
public int yachtID { get; set; }
public int yachtQuantity { get; set; }
public int yachtPrice { get; set; }
public int yachtName { get; set; }
}
现在在您的视图中绑定此 YachtID 以从购物车中删除项目
查看代码
<tbody class="customBody">
@foreach (var itemList in Model)
{
<tr class="customRow">
<td class="customData">@itemList.Name</td>
<td class="customData">@itemList.Quantity</td>
<td class="customData">@itemList.Price</td>
<td class="customData">@itemList.Total</td>
<td class="customData"><button class="btn-dark" onclick="@Url.Action('DeleteItem','Yacht1',new {@yatchID = @itemList.yatchID})>Delete</button></td>
</tr>
}
</tbody>
现在在控制器中添加方法(删除项目)
[HttpPost]
public ActionResult DeleteItem(int yachtID)
{
HomeController.basketItems.Remove(HomeController.basketItems.OfType<Basket>().Where(b => b.yachtID == yachtID).FirstOrDefault());
return RedirectToAction("Yacht1");
}