【问题标题】:Storing and displaying multiple query string in arraylist using session variables使用会话变量在arraylist中存储和显示多个查询字符串
【发布时间】:2015-11-11 07:22:57
【问题描述】:

我有一个带有产品网格的网络表单。当您单击产品时,它会将您带到一个页面,该页面显示带有“添加到购物车”按钮的单个产品。我想要做的是,当我单击“添加到购物车”按钮时,每次用户单击“添加到购物车”按钮时,会话都会将 productId 的查询字符串存储在数组列表中。我可以将它存储在会话变量中,但是当我想显示所有查询字符串时,只显示最近的一个。提前致谢。

下面是“加入购物车”按钮的代码:

protected void btnAdd_Click(object sender, EventArgs e)
    {
        string productId;

        ArrayList arProduct = new ArrayList();

        if (Request.QueryString.Get("ProductId") != null)
        {
            productId = Request.QueryString.Get("ProductId");
            arProduct.Add(productId);
        }

        Session["Cart"] = arProduct;
        Response.Redirect("Cart.aspx");
    }

下面是 Cart.aspx 页面加载的代码:

protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Cart"] != null)
        {
            lblProducts.Text = "Here are your products: " + "<ul>";
            ArrayList alProduct = new ArrayList();
            alProduct = (ArrayList)Session["Cart"];
            foreach (string item in alProduct)
            {
                lblProducts.Text +=  "<li>" + item + "</li>";
            }
            lblProducts.Text += "</ul>";
        }
    }

【问题讨论】:

    标签: c# asp.net .net arraylist session-variables


    【解决方案1】:

    当您单击“添加”时,您会创建一个新的arProduct 并每次将其放入Session["Cart"]。因此,先前的添加将被覆盖。您需要在添加事件处理程序中重用Session['Cart']

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        string productId;
    
        ArrayList arProduct = Session['Cart'] as ArrayList;
        if(arProduct == null)
        {
            arProduct = new ArrayList();
            Session['Cart'] = arProduct;
        }
    
        if (Request.QueryString.Get("ProductId") != null)
        {
            productId = Request.QueryString.Get("ProductId");
            arProduct.Add(productId);
        }
    
        Session["Cart"] = arProduct;
        Response.Redirect("Cart.aspx");
    }
    

    编辑:

    为了它的价值,我会将 arProduct 的代码放入一个属性中。并在 btnAdd_Click 处理程序和页面加载中使用它

    【讨论】:

    • 这很有意义。感谢您为我解决这个问题@Dbuggy
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 2014-05-25
    相关资源
    最近更新 更多