I am working with small ASP.NET MVC project - online store.
I have addToCart method which adds selected product to cart - it updates cart table in my db and showing cart view with its content. But I have problems. While db is updating correctly the view does not. I see that quantity of the product in my db is incremented correctly but quantity in view is not changed. I have to stop debugging my app in visual studia and restart it - then my view is showing correct data. What can be wrong?
am using LINQ to Entity. metod Add from cart repository:
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
}
method AddToCart from controller:
public void AddToCart(int pid, int quant, string usr)
{
_cartRep.Add(pid,quant,usr);
}
and method which returns cart View:
public ActionResult Cart()
{
IEnumerable<CartInfo> model = _cartRep.GetTrans();
return View(model);
}
Here is GetTrans() implementation:
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();
}
}
As you saw I have user name hard-coded. I have done it only for testing. If I would know that it is working I will improve the code. Thanks for a good advice with .FristOrDefault()
Html helpers get data from model state and not from model if you return the same view after form post. to get updated data in the view use post redirect get pattern or ModelState.Clear()
Are you returning the updated cart model to the view or the original cart without the updates?
Responding to comment
"after success I am using jquery to show cart" - How do you know the call to AddToCart succeeded? If it's a void method then unless the call errors (404/500) there's no way for the jQuery call to know it's succeeded. Have you got a race condition going on (the joys of asynchronous programming)?
For example:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With