I have my cart controller which I have made so the user cannot continue unless there is an item in the cart, the link is not shown.
However they can still just type the URL in and go to the AddressAndPayment page, how would I use a similar If statement in the AddressAndPayment controller, as used in the Cart controller to stop the user viewing the page.
Cart controller
public ActionResult Index()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
// Set up the ViewModel
ShoppingCartViewModel viewModel = new ShoppingCartViewModel
{
CartItems = cart.GetCartItems(),
CartTotal = cart.GetTotal()
};
if (viewModel.CartItems.Any())
{
ViewBag.CartStatus = "Proceed to checkout or ";
ViewBag.Link = "AddressAndPayment";
ViewBag.Link2 = "Checkout";
}
else
{
ViewBag.CartStatus = "Cart is empty please ";
ViewBag.Link = "Index";
ViewBag.Link2 = "Store";
}
// Return the view
return View(viewModel);
}
AddressAndCheckout controller
public ActionResult AddressAndPayment()
{
return View();
}
/// <summary>
/// Gets the address and payment from user
/// </summary>
/// <param name="values">payment values</param>
/// <returns></returns>
[HttpPost]
public ActionResult AddressAndPayment(FormCollection values)
{
var order = new Order();
TryUpdateModel(order);
order.Username = User.Identity.Name;
order.OrderDate = DateTime.Now;
//Order gets saved
storeDB.Orders.Add(order);
storeDB.SaveChanges();
//Order gets processed
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.CreateOrder(order);
//NEW TEST IF SAVES
storeDB.SaveChanges();
//Model.Product.stock = item.Product.stock - item.count;
return RedirectToAction("Complete",
new { id = order.OrderId });
}
Why don't you just redirect to the Cart page if the cart is empty?
public ActionResult AddressAndPayment()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
if(!cart.GetCartItems().Any())
return RedirectToAction("Index", "Cart"); // assuming Cart as controller name and Index as action name
return View();
}
You may do the same thing for the POST action.