我有我的推车控制器,所以除非购物车中有物品,否则用户无法继续操作,链接未显示。
但是他们仍然可以只输入URL并转到AddressAndPayment页面,我如何在AddressAndPayment控制器中使用类似的If语句,如Cart控制器中用来阻止用户查看页面。
推车控制器
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控制器
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 });
}
答案 0 :(得分:1)
如果购物车是空的,为什么不直接重定向到购物车页面?
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();
}
你可以对POST动作做同样的事情。
答案 1 :(得分:1)
交叉切割问题应该作为过滤器实现,以便您可以跨操作/控制器重复使用它们。在这种情况下,您可以制作MustHaveCartItemsAttribute
。
using System;
using System.Web.Mvc;
using System.Web.Routing;
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class MustHaveCartItemsAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var cart = ShoppingCart.GetCart(filterContext.HttpContext);
var ViewBag = filterContext.Controller.ViewBag;
if (!cart.GetCartItems.Any())
{
ViewBag.CartStatus = "Cart is empty please ";
ViewBag.Link = "Index";
ViewBag.Link2 = "Store";
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
new { controller = "Cart", action = "Index" }));
}
}
}
[MustHaveCartItems]
public ActionResult AddressAndPayment()
{
return View();
}