使用实体模型将ArrayList绑定到Repeater控件

本文关键字:Repeater 控件 绑定 ArrayList 实体模型 | 更新日期: 2023-09-27 18:21:48

我正在创建一个购物车。用户将转到产品的各个页面,然后单击"添加到购物车"按钮。单击该按钮后,ProductId将存储在会话["Cart"]中的数组列表中。当它们转到Cart.aspx时,中继器将显示阵列列表中的所有项目。我不知道如何将数组列表与实体模型一起正确使用。

以下是我迄今为止对背后的代码的了解:

if (Session["Cart"] != null)
        {
            using (ProjectEntities myEntities = new ProjectEntities())
            {
                ArrayList alProduct = new ArrayList();
                alProduct = (ArrayList)Session["Cart"];
                var product = (from p in myEntities.Products
                               where p.ProductId == Convert.ToInt32(alProduct)
                               select new { p.ProductName });
                Repeater1.DataSource = product.ToList();
                Repeater1.DataBind();
            }
        }

以下是Cart.aspx的标记

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
            <table>
                <tr>
                    <td>
                        <asp:Label ID="lblProductName" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
                </tr>
            </table>
        </ItemTemplate>
    </asp:Repeater>
</asp:Content>

使用实体模型将ArrayList绑定到Repeater控件

代码的第一个问题是:p.ProductId == Convert.ToInt32(alProduct)。由于alProduct是一个ArrayList,它永远不会转换为integer,并且会引发运行时异常。像这样更改您的查询并使用Contains:-

var product = (from p in myEntities.Products
               where alProduct.Contains(p.ProductId)
               select p.ProductName).ToList();

由于您只选择了一个项目,即ProductName,因此无需投影匿名类型。

此外,在从会话分配值之前,不需要实例化ArrayList,尽管在运行product查询之前应该检查null。我建议您使用ArrayList的通用版本,即List<int>,而不是ArrayList。