[SOLVED] Display message when user clicks on "Add To Cart" button in ASP.NET MVC controller

Issue

I am creating a shopping website in ASP.NET MVC.

What I want to do is display a message "Your products are added to cart" when the user clicks on the "Add To Cart" button. I don’t know how to redirect on any page I just show a message.

Here is my controller

public ActionResult AddtoCart(int id)
{
    List<Product> list;

    if (Session["MyCart"] == null)
    { 
        list = new List<Product>();
    }
    else
    { 
        list = (List<Product>)Session["MyCart"]; 
    }

    list.Add(db.Products.Where(p => p.Product_ID == id).FirstOrDefault());
    Session["MyCart"] = list;

    list[list.Count - 1].Pro_Quantity = 1;
    ViewBag.cart = list.Count();

    Session["count"] = Convert.ToInt32(Session["count"]) + 1;

    return RedirectToAction("Shop", "Home");
}

Here is my "Add to Cart" button:

<a href="@Url.Action("AddtoCart","Home", new {id=p.Product_ID })" class="filled-button">
    Add to Cart
</a>

Solution

One common way to accomplish that is to add a value to the ViewBag in your controller action, then in the view that action returns, check whether that ViewBag value is set, and if so display your message.

However, the ViewBag only lasts for the duration of a single request. A Redirect or RedirectToAction is a new request. To send data between one request and another in MVC, you have to use TempData instead.

(If you want to learn more about when ViewBag and TempData are used and their lifecycles, see ViewBag/ViewData Lifecycle).

So since your controller action returns RedirectToAction, you have to use TempData in the first action. So in your AddToCart action, you’d add:

TempData["ItemAdded"] = true;

Then, in the Shop action, you can pick up that TempData value and use it to set a value in the ViewBag so it can be displayed in the view.

So in your Shop action, you can add something like this:

if (TempData.ContainsKey("ItemAdded") && (bool)TempData["ItemAdded"])
{
    ViewBag.Message = "Your products are added to cart";
}

Finally, in your Shop view, you’d do something like this:

@if (!string.IsNullOrWhiteSpace(ViewBag.Message))
{
    <div class="message">
        @ViewBag.Message
    </div>
}

Edit – to address comment about wanting a pop-up message

If you want to update the current page without navigating away, you’re going to have to use AJAX.

Here’s two simple ways of accomplishing that. Which one you choose depends on whether you’ve already got a form on the page, how you’ve accomplished things elsewhere in this project, how your company prefers things to be done, etc.

1) Using jQuery $.ajax()

In your View, you’ll want to change your button to something like this:

<a class="filled-button" onclick="addToCart(event, '@(p.Product_ID)')">
    Add to Cart
</a>
<!-- or -->
<button type="button" class="filled-button" onclick="addToCart('@(p.Product_ID)')">
    Add to Cart
</button>

(You can, of course, assign the click events inside your $(document).ready function, rather than using the onclick attribute.)

Also in your View, you’ll add some JavaScript like this:

var addToCartUrl = "@Url.Action("AddtoCart", "Home")";

// you only need the productId parameter if you're not passing in the event
function addToCart(e, productId) {
    // prevent navigating away from the page on <a> tag click
    e.preventDefault();

    // make ajax request
    $.ajax({
        url: addToCartUrl,
        data: { id: productId },
        success: function (data) {
            // display your message however you want
        }
    });
}

In your Controller Action:

// change the last line from:
// return RedirectToAction("Shop", "Home");
// to:
return Json("Your products are added to cart", JsonRequestBehavior.AllowGet);

2) Using MVC’s built-in ajax form

This method isn’t that drastically different from the previous method.

First, you’ll surround the product section of your View with a form, like so:

@using (Ajax.BeginForm("AddtoCart", "Home", new AjaxOptions { OnSuccess = "productAddedToCart" }))
{
    ...
}

And you’ll change your "Add to Cart" buttons to submit buttons:

<button type="submit" name="id" value="@(p.Product_ID)" class="filled-button">
    Add to Cart
</button>

Just like method #1, you’ll need to return JSON from your Controller Action:

// from: return RedirectToAction("Shop", "Home");
return Json("Your products are added to cart", JsonRequestBehavior.AllowGet);

Finally, the OnSuccess JavaScript function will look just like it did in method 1:

function productAddedToCart (data) {
    // display your message however you want
}

Answered By – CarenRose

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *