【问题标题】:How can I find My Cart Total With Repeater in OnItemDataBound (ASP.NET)如何在 OnItemDataBound (ASP.NET) 中找到带有中继器的我的购物车总数
【发布时间】:2018-02-27 18:19:38
【问题描述】:

我想查找购物车中商品的总价。但是,如果产品有折扣价,我必须得到折扣价,如果没有折扣价,我必须得到总价的正常价格。

这是我的中继器:

<asp:Repeater ID="RptrShoppingCart" runat="server" OnItemDataBound="RptrShoppingCart_ItemDataBound">
    <ItemTemplate>
        <asp:Label ID="LblProductPrice" runat="server" Text='<%#int.Parse(Eval("DiscountedPrice").ToString()) > 0 ? Convert.ToDecimal(Eval("DiscountedPrice")) * Convert.ToDecimal(Eval("Piece")) : Convert.ToDecimal(Eval("NormalPrice")) * Convert.ToDecimal(Eval("Piece")) %>'></asp:Label>
    </ItemTemplate>
</asp:Repeater>
<asp:Label ID="LblShoppingCartTotal" runat="server"></asp:Label>

注意:我不是故意写中继器填充代码

还有我的 C# 代码:

decimal total = 0;
protected void RptrShoppingCart_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    DataRow dr = function.GetDataRow("SELECT Product.DiscountedPrice FROM ShoppingCart AS SC INNER JOIN Product AS P ON SC.ProductID = P.ID WHERE SC.UserID = '" + Session["UserID"] + "'");

    DataRowView item = e.Item.DataItem as DataRowView;

    if (Convert.ToDecimal(dr["DiscountedPrice"]) > 0) // This means if it is a discounted price
    {
        total += Convert.ToDecimal(item["DiscountedPrice"]) * Convert.ToDecimal(item["Piece"]);
    }
    else
    {
        total += Convert.ToDecimal(item["NormalPrice"]) * Convert.ToDecimal(item["Piece"]);
    }
    LblShoppingCartTotal.Text = string.Format("{0:C}", total);
}

例如:我添加一个正常价格为 10 美元但折扣价为 8 美元的 1 件产品,并添加一个正常价格为 20 美元但没有折扣价的 2 件产品。

购物车的总和应该是:(1 x 8$) + (2 x 20$) = 48$,但我的购物车总数看起来是 8$。我哪里做错了?

【问题讨论】:

  • 不要在ItemDataBound 事件中这样做。从原始数据计算您的总数,无论您绑定到控件的是什么。

标签: c# asp.net repeater shopping-cart


【解决方案1】:

您做得很好,您只是在页面生命周期的错误部分设置了标签。

这是最后的生命周期事件之一,所以你不会出错。

    protected override void OnPreRender(EventArgs e)
    {
        LblShoppingCartTotal.Text = string.Format("{0:C}", total);
    }

【讨论】:

    猜你喜欢
    • 2019-12-09
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多