繁体   English   中英

当用户单击 ASP.NET MVC controller 中的“添加到购物车”按钮时显示消息

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

我正在 ASP.NET MVC 中创建一个购物网站。

我想要做的是在用户单击“添加到购物车”按钮时显示一条消息“您的产品已添加到购物车”。 我不知道如何在任何页面上重定向,我只是显示一条消息。

这是我的 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");
}

这是我的“添加到购物车”按钮:

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

完成此操作的一种常见方法是在 controller 操作中向ViewBag添加一个值,然后在该操作返回的视图中,检查是否设置了ViewBag值,如果设置了则显示您的消息。

但是ViewBag仅在单个请求期间持续。 RedirectRedirectToAction是一个请求。 要在 MVC 中的一个请求与另一个请求之间发送数据,您必须改用TempData

(如果您想详细了解何时使用ViewBagTempData以及它们的生命周期,请参阅ViewBag/ViewData Lifecycle )。

因此,由于您的 controller 操作返回RedirectToAction ,因此您必须在第一个操作中使用TempData 因此,在您的AddToCart操作中,您将添加:

TempData["ItemAdded"] = true;

然后,在Shop操作中,您可以获取该 TempData 值并使用它在TempData中设置一个值, ViewBag它可以显示在视图中。

因此,在您的Shop操作中,您可以添加如下内容:

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

最后,在您的Shop视图中,您将执行如下操作:

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

编辑 - 解决关于想要弹出消息的评论

如果您想在不离开的情况下更新当前页面,您将不得不使用 AJAX。

这里有两种简单的方法来实现这一点。 你选择哪一个取决于你是否已经在页面上有一个表格,你在这个项目的其他地方是如何完成事情的,你的公司喜欢如何完成事情,等等。

1) 使用 jQuery $.ajax()

在您的视图中,您需要将按钮更改为如下所示:

<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>

(当然,您可以在$(document).ready function 中分配点击事件,而不是使用onclick属性。)

同样在您的视图中,您将像这样添加一些 JavaScript:

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
        }
    });
}

在您的 Controller 操作中:

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

2)使用MVC内置的ajax表单

这种方法与以前的方法并没有太大的不同。

首先,您将用一个表单包围视图的产品部分,如下所示:

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

您将更改“添加到购物车”按钮以submit按钮:

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

就像方法 #1 一样,您需要从 Controller 操作中返回 JSON:

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

最后, OnSuccess JavaScript function 看起来就像方法 1 中那样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM