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.
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.:
Also, in a RESTful application, you should ideally be using a POST method to add to the cart.