5

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()

crocodillez
  • 51
  • 1
  • 3
  • Is there any chance we can also see the code for GetTrans() from the the cart repository? There are so many potential issues in your code that I can see at the moment, for example: you pass in a quantity of products to Add(pid,quant,usr) and then you've hard-coded the user name and quantity into the search and addition; What if the user doesn't have that product in their cart to start with, ".First()" will throw an exception (.FirstOrDefault() will give you a null if it can't find one), etc - I wouldn't be surprised if you were returning the wrong users cart at this point. – Zhaph - Ben Duguid May 14 '10 at 13:58

3 Answers3

8

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()

Alexander Taran
  • 6,655
  • 2
  • 39
  • 60
1

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:

  1. jQuery calls AddToCart which starts processing.
  2. Void method, jQuery doesn't wait for a "response" (there isn't going to be one) so hands off to Success method.
  3. jQuery calls ShowCart (or similar) which returns the un-updated cart.
  4. AddToCart completes, saving the updated version of the cart to the database.
  5. The next time ShowCart runs, it returns the updated cart.
Zhaph - Ben Duguid
  • 26,785
  • 5
  • 80
  • 117
  • In my controller I have method AddToCart of type void which adds product to cart (invokes method from model Add from cart repo). To add product to cart I am using jquery which invokes method AddToCart from controller with specified parameters. After success I am using jquery to show cart - invoking method which return cart view which is not updated... – crocodillez May 13 '10 at 10:55
  • in fith paragraph you wrote that with next run of ShowCart updated view should be returned. but in my app only restarting of application in vs causes update of cart view... in cart repo i am using SaveChanges() method which updates entities. When application is executing after adding product to cart I see that proper record in db is updated correctly, but why view does not get updated data? – crocodillez May 13 '10 at 12:17
  • @crocodillez: No, it's not a bad idea to update that way, I'd just recommend that you actually return something (i.e. the updated cart object) from your AddToCart method. – Zhaph - Ben Duguid May 13 '10 at 12:23
  • @crocodillez: Ok, I see what you mean. It sounds like you're only loading the data for the cart once, possibly into an object disconnected from the database - what are you using to talk to the database - LINQ to SQL/Entity Framework, some other ORM, etc? **Without seeing the code you are using** I can only guess as to what the problem is - are you using a Static object that isn't updating properly? etc. – Zhaph - Ben Duguid May 13 '10 at 12:27
0

I 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);
    }
crocodillez
  • 51
  • 1
  • 3