I would like to call a method from my "ShoppingCart" model class to my HomeController. If Action "Complete" is executed, I want the method "EmptyCart" to happen. Is there a good way to do this?
This is the modelclass:
public class ShoppingCart
{
FotobutikkJLCDbContext db = new FotobutikkJLCDbContext();
string ShoppingCartId { get; set; }
public void EmptyCart()
{
var cartItems = db.Carts.Where(cart => cart.CartId == ShoppingCartId);
foreach (var cartItem in cartItems)
{
db.Carts.Remove(cartItem);
}
// Save changes
db.SaveChanges();
}
And this is the ActionResult:
public class HomeController : Controller
{
public ActionResult Complete()
{
ViewBag.Message = "Complete";
return View();
}
}
Your model needs to be passed back to the controller for the controller to know about it, then just call EmptyCart()
.
public ActionResult Complete(ShoppingCart shoppingCart)
{
ViewBag.Message = "Complete";
shoppingCart.EmptyCart();
return View();
}