0

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>
CarenRose
  • 1,266
  • 1
  • 12
  • 24
Kamran Ali
  • 59
  • 7
  • 1
    You say you don't know how to redirect....yet you have a clear RedirectToAction result that you're returning. Have you considered passing some sort of message there as part of the URL? Perhaps your query string could include something like `?productadded=1` and then on the page the user is redirected to, check for the presence of that query string. If present, show the message. That seems pretty straightforward. Can you give that a try? – mason Feb 22 '22 at 17:43
  • you send ajax request when add to cart button clicked and return a message from your action result instead of redirection. base the message returned back you can show it to user. – Rajesh G Feb 22 '22 at 17:53
  • Can you Please edit my code and show me how i can do it? – Kamran Ali Feb 22 '22 at 18:19
  • 1
    Do you want the page to not jump when adding to the shopping cart, and only display information "Your products are added to cart"on the current page? – Qing Guo Feb 23 '22 at 05:58
  • Yes Exaclty Can You please Help – Kamran Ali Feb 24 '22 at 19:27

1 Answers1

1

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
}
CarenRose
  • 1,266
  • 1
  • 12
  • 24
  • Yes it is working But actually I want a Pop up message ? – Kamran Ali Feb 24 '22 at 19:42
  • Thanks I have applied your it is Working But it doesn't show Products in Cart suddenly until I refresh the page Manually... I am using Session to Add Products in cart.......... – Kamran Ali Feb 27 '22 at 09:21
  • If I'm understanding correctly, you also want to update the number of items in the cart on the page with that ajax call? If so, you just have to return an object in your JSON rather than just a string. – CarenRose Mar 01 '22 at 23:23
  • Yes You Understand Correctly Can You tell me How i Can do it? How i can return string and object both? – Kamran Ali Mar 03 '22 at 10:24
  • @KamranAli you don't return both a string and object, you just create an anonymous object and return that as JSON. `return Json({ message = "Your products ...", cartCount = 5 })` – CarenRose Mar 03 '22 at 15:49