查看问题 – 数据库更新后不刷新

我正在使用小型ASP.NET MVC项目 – 在线商店。

我有addToCart方法,它将所选产品添加到购物车 – 它更新我的数据库中的购物车表并显示购物车视图及其内容。 但我有问题。 db正确更新时视图没有。 我看到我的数据库中的产品数量正确递增,但视图中的数量不会更改。 我必须停止在视觉研究中调试我的应用程序并重新启动它 – 然后我的视图显示正确的数据。 有什么不对?

我正在使用LINQ to Entity。 metod从购物车存储库添加:

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 model = _cartRep.GetTrans(); return View(model); } 

这是GetTrans()实现:

  public IEnumerable 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()提出的建议。

如果在表单发布后返回相同的视图,则Html帮助程序从模型状态而不是从模型获取数据。 在视图中获取更新数据使用post redirect get pattern或ModelState.Clear()

您是否在没有更新的情况下将更新的购物车型号退回到视图或原始购物车?

回应评论

“成功后我使用jquery来显示购物车” – 你怎么知道对AddToCart的调用成功了? 如果它是一个void方法,那么除非调用错误(404/500),否则jQuery调用无法知道它是否成功。 你有没有竞争条件(异步编程的乐趣)?

例如:

  1. jQuery调用AddToCart开始处理。
  2. Void方法,jQuery不等待“响应”(不会有一个)所以交给Success方法。
  3. jQuery调用ShowCart(或类似的)返回未更新的购物车。
  4. AddToCart完成,将更新版本的购物车保存到数据库。
  5. 下次ShowCart运行时,它会返回更新的购物车。

我正在使用LINQ to Entity。 metod从购物车存储库添加:

  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 model = _cartRep.GetTrans(); return View(model); }