gpt4 book ai didi

c# - View 问题 - 数据库更新后它不刷新

转载 作者:行者123 更新时间:2023-11-30 14:04:06 26 4
gpt4 key购买 nike

我正在处理小型 ASP.NET MVC 项目 - 在线商店。

我有将所选产品添加到购物车的 addToCart 方法 - 它更新我的数据库中的购物车表并显示购物车 View 及其内容。但我有问题。虽然数据库正在正确更新,但 View 没有。我看到我的数据库中的产品数量正确增加,但 View 中的数量没有改变。我必须停止在 visual studia 中调试我的应用程序并重新启动它 - 然后我的 View 显示正确的数据。有什么问题吗?

我正在使用 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
}

Controller 中的 AddToCart 方法:

public void AddToCart(int pid, int quant, string usr)
{
_cartRep.Add(pid,quant,usr);
}

返 repo 物车 View 的方法:

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() 的好建议

最佳答案

如果您在提交表单后返回相同的 View ,则 Html 助手从模型状态获取数据,而不是从模型获取数据。要在 View 中获取更新的数据,请使用重定向后获取模式或 ModelState.Clear()

关于c# - View 问题 - 数据库更新后它不刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2825672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com