制作购物车并在ASP.Net中添加折扣



我正在尝试学习ASP.NET MVC,我正在尝试做的一个项目是创建一个包含几本书的网站。当你添加几本同一系列的书时,它应该会有折扣,但不适用于购物车中其他系列的任何书(例如,2部漫威漫画会给这些书打9折,但DC漫画不会有任何折扣(。

然而,我遇到的问题是首先创建一个购物车,我遵循了以下教程:

https://learningprogramming.net/net/asp-net-core-mvc/build-shopping-cart-with-session-in-asp-net-core-mvc/

但它似乎已经过时了,我得到了一个错误:

模棱两可的ActionException:多个操作匹配。以下操作与路线数据匹配,并满足所有约束:

BookStore.Controllers.ProductController.Index(BookStore(页码:/索引

我不知道为什么,我是路由的新手,所以我可以假设我错过了什么,我会包括下面的代码:

namespace BookStore.Controllers
{
[Route("product")]
public class ProductController : Controller
{
[Route("")]
[Route("index")]
[Route("~/")]
public IActionResult Index()
{
ProductModel productModel = new ProductModel();
ViewBag.products = productModel.findAll();
return View();
}
}
}
namespace BookStore.Controllers
{
[Route("cart")]
public class CartController : Controller
{
[Route("index")]
public IActionResult Index()
{
var cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
ViewBag.cart = cart;
ViewBag.total = cart.Sum(item => item.Product.Price * item.Quantity);
return View();
}
[Route("buy/{id}")]
public IActionResult Buy(string id)
{
ProductModel productModel = new ProductModel();
if (SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart") == null)
{
List<Item> cart = new List<Item>();
cart.Add(new Item { Product = productModel.find(id), Quantity = 1 });
SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
}
else
{
List<Item> cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
int index = isExist(id);
if (index != -1)
{
cart[index].Quantity++;
}
else
{
cart.Add(new Item { Product = productModel.find(id), Quantity = 1 });
}
SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
}
return RedirectToAction("Index");
}
}
}

我也一直在看这个

https://learn.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/create_the_data_access_layer

因为它使用的是最新版本的

您可以将Name属性添加到Controller方法Index的HTTP谓词属性中。在你的情况下,你可以这样做:

//ProductController Index method
[Route("")]
[Route("index")]
[Route("~/")]
[HttpGet(Name = "Get my products")]
public IActionResult Index()
//CartController Index method
[Route("index")]
[HttpGet(Name = "Get my cart data")]
public IActionResult Index()

你可以在这里阅读更多为什么你不能在不同的控制器上有两个同名的路径

您还需要正确设置routes

app.UseMvc(routes =>  
{  
routes.MapRoute(
name: "ByProduct",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Product", action = "Index"});  
routes.MapRoute(  
name: "default",  
template: "{controller=Home}/{action=Index}/{id?}");  
});

最新更新