views:

103

answers:

3

I have an Action that basically adds an item to a cart, the only way the cart is known is by checking the cookie, here is the flow of logic, please let me know if you see any issue...

/order/add/[id] is called via GET

action checks for cookie, if no cookie found, it makes a new cart, writes the identifier to the cookie, and adds the item to the database with a relation to the cart created

if cookie is found, it gets the cart identifier from the cookie, gets the cart object, adds the item to the database with a relation to the cart found

so it's basically like...

action add(int id){

if(cookie is there)
    cart = getcart(cookievalue)
else
    cart = makecart()
    createcookie(cart.id)

additemtocart(cart.id, id)

return "success";
}

Seem right? I can't really thing of another way that would make sense.

+1  A: 

Looks okay to me.

/order/add/[id] is called via GET

1) A cart is not yet an order, but it's just terminology.

2) It is preferred to use POST (PUT) to modify data.

3) With storing your temporary carts in the database, don't forget to schedule some cleanup service running to erase old abandoned carts.

Developer Art
A: 

About the (only) thing i can think of is whether you need to store anything in the database.

If you allow people to browse on one computer and then checkout from another then sure, you need to store the selected items in a database.

If however you don't allow that then you could hold the items selected in the cookie which saves a database trip.

griegs
+1  A: 

Your logic looks ok, though i'd consider whether or not you need to store the cart contents in a database. Unless you have a good reason i'd be tempted just to add it to the session.

I'd also look into creating a custom model binder for the cart object, which would either pass in a new cart instance or one instantiated from the visitors cookie. That way your controller looks much simpler, e.g.:

public ActionResult Add(Cart cart, int id)
{
    AddItemToCart(cart, id);
    return View();
}

Also, in a RESTful application, you should ideally be using a POST method to add to the cart.

richeym