【发布时间】:2010-05-13 09:30:15
【问题描述】:
我正在使用小型 ASP.NET MVC 项目 - 在线商店。
我有 addToCart 方法,可以将选定的产品添加到购物车 - 它更新我的数据库中的购物车表并显示购物车视图及其内容。但我有问题。虽然 db 正确更新,但视图没有正确更新。我看到我的数据库中的产品数量正确增加,但视图中的数量没有改变。我必须停止在 Visual studia 中调试我的应用程序并重新启动它 - 然后我的视图显示正确的数据。有什么问题?
我正在使用 LINQ to Entity。从购物车存储库添加方法:
public void Add(int product, int quantity, string user)
{
Cart cart = null;
cart = (from c in de.Cart
where (c.userName == "testUser" && c.productId == product)
select c).First();
// query is searching for existing product of testUser and id specified in parameter in cart and get it
cart.quantity += 1; //increment quantity
de.SaveChanges(); // save entity
}
来自控制器的 AddToCart 方法:
public void AddToCart(int pid, int quant, string usr)
{
_cartRep.Add(pid,quant,usr);
}
返回购物车视图的方法:
public ActionResult Cart()
{
IEnumerable<CartInfo> model = _cartRep.GetTrans();
return View(model);
}
这里是 GetTrans() 实现:
public IEnumerable<CartInfo> GetTrans()
{
using (DBEntities de = new DBEntities())
{
return (from c in de.Cart
where (c.userName == "testUser")
select new CartInfo
{
Id = c.id,
ProductId = c.productId,
Quntity = c.quantity,
Realized = c.realized,
UserName = c.userName,
Value = c.value,
Products = (from p in de.Product
where (p.id == c.productId)
select new ProductInfo
{
Category = p.Category,
Desc = p.Description,
Id = p.id,
Image = p.Image,
Name = p.Name,
Quntity = p.Quantity,
Price = p.Price
})
}).ToList();
}
}
如您所见,我的用户名是硬编码的。我这样做只是为了测试。如果我知道它正在工作,我会改进代码。感谢 .FristOrDefault() 的好建议
【问题讨论】:
-
我们是否有机会从购物车存储库中看到 GetTrans() 的代码?我目前可以看到您的代码中有很多潜在问题,例如:您将一定数量的产品传递给 Add(pid,quant,usr) 然后您将用户名和数量硬编码到搜索和添加;如果用户的购物车中没有该产品,“.First()”会抛出异常(如果找不到,.FirstOrDefault() 会给你一个空值)等等 - 我会如果您此时返回错误的用户购物车,请不要感到惊讶。
标签: c# asp.net-mvc model-view-controller