Michael D.
Michael D.

Reputation: 1319

Asp.net MVC eCommerce app - Add To Cart implementation

Let say I am rendering list of products with Add To Cart link / button next to each.

I also have a CartController with AddToCart Action that accept a parameter of Product type.

After product is added to cart user should stay on the same page (Product list) - not to be redirected to Cart or something.

I am rendering Cart summary partial view that should update itself.

So my question is about implementation of the Add To Cart link / button.

Should I use: Html.ActionLink(...)

or Html.BeginForm() and Submit button.

Maybe there is other ways...

How do I send Product info in each case?

Thanks

Upvotes: 1

Views: 3007

Answers (3)

Andrew Siemer
Andrew Siemer

Reputation: 10276

I suggest using a jQuery.post() request to your CartController.AddToCart. Make AddToCart a partial view. And then show a modal popup (div on top of your page) that shows that the product was added to the cart...then do a fade out!

Keep it simple.

Now keep in mind that some of your users won't be able to support jquery/javascript. So make the initial add to cart button post to an add to cart page (not partial page..full page)...which can return them to the original page. Then spot weld your jquery function on top of the add to cart button. This way you cover both worlds nicely.

Take a look at the concept of unobtrusive javascript/jquery.

Upvotes: 2

James S
James S

Reputation: 3374

Again I'd take into consideration what happens if the user doesn't have javascript. It's not very likely these days, but do you want to lose a sale just because someone accidently turned off javascript?

So what I'd do is create the somewhat typical AddToCart link (<a class="add" href="/Shop/AddToCart/5">). The AddToCart controller would then do it's stuff and redirect back to the product listing page (you might have to pass a parameter to specify which page to go back to).

So that's the first step to consider -- javascript turned off. Now you can think about how to do it with javascript.

Capture the click event ( $('a.add').click(...) ) and then you can do two things. One would be to call the URL (you can get it out of the event object) and then separately update the cart. You can also add a parameter to the URL so that it displays the cart partial view, doing something like (written from memory):

$('a.add').click(function(event) { $('#cart').load(event.target.attr('href') + '&showcart=1');

James

Upvotes: 1

Jaime
Jaime

Reputation: 6814

The way I do it is to have a form for each add button (with maybe the quantity also), since you want your AddToCart action only receive POST actions anyway, that way you process all the add to cart logic and then redirect to your main catalog view (or something like that :)

Upvotes: 1

Related Questions