显示数据项和详细信息

作者 :Erik Reitan

本教程系列介绍如何使用 ASP.NET 4.7 和 Microsoft Visual Studio 2017 生成 ASP.NET Web Forms应用程序。

本教程介绍如何使用 ASP.NET Web Forms 和 Entity Framework Code First 显示数据项和数据项详细信息。 本教程以上一个“UI 和导航”教程为基础,作为 Wingtip 玩具商店教程系列的一部分。 完成本教程后,你将在 ProductsList.aspx 页面上看到产品,在 ProductDetails.aspx 页面上看到产品的详细信息。

将了解如何执行以下操作:

  • 添加数据控件以显示数据库中的产品
  • 将数据控件连接到所选数据
  • 添加数据控件以显示数据库中的产品详细信息
  • 从查询字符串中检索值,并使用该值限制从数据库中检索的数据

本教程中介绍的功能:

  • 模型绑定
  • 值提供程序

添加数据控件

可以使用几个不同的选项将数据绑定到服务器控件。 最常见的子命令包括:

  • 添加数据源控件
  • 手动添加代码
  • 使用模型绑定

使用数据源控件绑定数据

添加数据源控件可将数据源控件链接到显示数据的控件。 使用此方法,可以声明方式(而不是以编程方式)将服务器端控件连接到数据源。

手动编写代码以绑定数据

手动编码涉及:

  1. 读取值
  2. 检查是否为 null
  3. 将其转换为适当的类型
  4. 检查转换是否成功
  5. 在查询中使用值

使用此方法可以完全控制数据访问逻辑。

使用模型绑定绑定数据

模型绑定使你能够使用更少的代码绑定结果,并使你能够在整个应用程序中重复使用该功能。 它简化了使用以代码为中心的数据访问逻辑,同时仍然提供丰富的数据绑定框架。

显示产品

在本教程中,你将使用模型绑定来绑定数据。 若要配置数据控件以使用模型绑定来选择数据,请在页面代码中将控件的 SelectMethod 属性设置为方法名称。 数据控件在页面生命周期中的适当时间调用 方法,并自动绑定返回的数据。 无需显式调用 DataBind 方法。

  1. 解决方案资源管理器 中,打开 ProductList.aspx

  2. 将现有标记替换为以下标记:

    <%@ Page Title="Products" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" 
             CodeBehind="ProductList.aspx.cs" Inherits="WingtipToys.ProductList" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
        <section>
            <div>
                <hgroup>
                    <h2><%: Page.Title %></h2>
                </hgroup>
    
                <asp:ListView ID="productList" runat="server" 
                    DataKeyNames="ProductID" GroupItemCount="4"
                    ItemType="WingtipToys.Models.Product" SelectMethod="GetProducts">
                    <EmptyDataTemplate>
                        <table >
                            <tr>
                                <td>No data was returned.</td>
                            </tr>
                        </table>
                    </EmptyDataTemplate>
                    <EmptyItemTemplate>
                        <td/>
                    </EmptyItemTemplate>
                    <GroupTemplate>
                        <tr id="itemPlaceholderContainer" runat="server">
                            <td id="itemPlaceholder" runat="server"></td>
                        </tr>
                    </GroupTemplate>
                    <ItemTemplate>
                        <td runat="server">
                            <table>
                                <tr>
                                    <td>
                                        <a href="ProductDetails.aspx?productID=<%#:Item.ProductID%>">
                                            <img src="/Catalog/Images/Thumbs/<%#:Item.ImagePath%>"
                                                width="100" height="75" style="border: solid" /></a>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <a href="ProductDetails.aspx?productID=<%#:Item.ProductID%>">
                                            <span>
                                                <%#:Item.ProductName%>
                                            </span>
                                        </a>
                                        <br />
                                        <span>
                                            <b>Price: </b><%#:String.Format("{0:c}", Item.UnitPrice)%>
                                        </span>
                                        <br />
                                    </td>
                                </tr>
                                <tr>
                                    <td>&nbsp;</td>
                                </tr>
                            </table>
                            </p>
                        </td>
                    </ItemTemplate>
                    <LayoutTemplate>
                        <table style="width:100%;">
                            <tbody>
                                <tr>
                                    <td>
                                        <table id="groupPlaceholderContainer" runat="server" style="width:100%">
                                            <tr id="groupPlaceholder"></tr>
                                        </table>
                                    </td>
                                </tr>
                                <tr>
                                    <td></td>
                                </tr>
                                <tr></tr>
                            </tbody>
                        </table>
                    </LayoutTemplate>
                </asp:ListView>
            </div>
        </section>
    </asp:Content>
    

此代码使用名为 的 productListListView 控件来显示产品。

<asp:ListView ID="productList" runat="server"

使用模板和样式,可以定义 ListView 控件显示数据的方式。 它对于任何重复结构中的数据都很有用。 虽然此 ListView 示例仅显示数据库数据,但你也可以在没有代码的情况下让用户编辑、插入和删除数据,以及对数据进行排序和分页。

通过在 ListView 控件中设置 ItemType 属性,数据绑定表达式Item可用,并且控件将变为强类型。 如上一教程中所述,可以使用 IntelliSense 选择 Item 对象详细信息,例如指定 ProductName

显示数据项和详细信息 - IntelliSense

你还使用模型绑定来指定 SelectMethod 值。 此值 (GetProducts) 对应于将添加到代码隐藏以在下一步中显示产品的方法。

添加代码以显示产品

在此步骤中,你将添加代码以使用数据库中的产品数据填充 ListView 控件。 该代码支持显示所有产品和单个类别产品。

  1. “解决方案资源管理器”中,右键单击“ProductList.aspx”,然后选择“查看代码”。

  2. ProductList.aspx.cs 文件中的现有代码替换为以下代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using WingtipToys.Models;
    using System.Web.ModelBinding;
    
    namespace WingtipToys
    {
        public partial class ProductList : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            public IQueryable<Product> GetProducts([QueryString("id")] int? categoryId)
            {
                var _db = new WingtipToys.Models.ProductContext();
                    IQueryable<Product> query = _db.Products;
                    if (categoryId.HasValue && categoryId > 0)
                    {
                        query = query.Where(p => p.CategoryID == categoryId);
                    }
                    return query;
            }
        }
    }
    

此代码显示 GetProductsListView 控件的属性 ItemTypeProductList.aspx 页中引用的方法。 为了将结果限制为特定的数据库类别,代码设置categoryId在导航到 ProductList.aspx 页面时传递给 ProductList.aspx 页的查询字符串值中的值。 QueryStringAttribute命名空间中的 System.Web.ModelBinding 类用于检索查询字符串变量 id的值。 这会指示模型绑定尝试在运行时将查询字符串中的值绑定到 categoryId 参数。

将有效类别作为查询字符串传递到页面时,查询结果仅限于数据库中与值匹配的产品 categoryId 。 例如,如果 ProductsList.aspx 页面 URL 为:

http://localhost/ProductList.aspx?id=1

该页仅显示 等于 1的产品categoryId

如果在调用 ProductList.aspx 页面时未包含查询字符串,则显示所有产品。

这些方法的值源称为 值提供程序 (如 QueryString) ,指示要使用的值提供程序的参数属性称为 值提供程序 属性 (如 id) 。 ASP.NET 包括Web Forms应用程序中所有典型用户输入源的值提供程序和相应的属性,例如查询字符串、Cookie、表单值、控件、视图状态、会话状态和配置文件属性。 还可以编写自定义值提供程序。

运行应用程序

立即运行应用程序,查看所有产品或类别的产品。

  1. 在 Visual Studio 中按 F5 运行应用程序。
    浏览器将打开并显示 Default.aspx 页。

  2. 从产品类别导航菜单中选择“ 汽车 ”。
    “ProductList.aspx”页仅显示“汽车”类别产品。 在本教程的后面部分,你将显示产品详细信息。

    显示数据项和详细信息 - 汽车

  3. 从顶部导航菜单中选择“ 产品 ”。
    同样, 将显示 ProductList.aspx 页,但这次显示整个产品列表。

    显示整个产品列表的 ProductList.aspx 页的屏幕截图。

  4. 关闭浏览器并返回到 Visual Studio。

添加数据控件以显示产品详细信息

接下来,你将修改在上一教程中添加的 ProductDetails.aspx 页中的标记,以显示特定产品信息。

  1. 解决方案资源管理器 中,打开 ProductDetails.aspx

  2. 将现有标记替换为以下标记:

    <%@ Page Title="Product Details" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" 
             CodeBehind="ProductDetails.aspx.cs" Inherits="WingtipToys.ProductDetails" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
        <asp:FormView ID="productDetail" runat="server" ItemType="WingtipToys.Models.Product" SelectMethod ="GetProduct" RenderOuterTable="false">
            <ItemTemplate>
                <div>
                    <h1><%#:Item.ProductName %></h1>
                </div>
                <br />
                <table>
                    <tr>
                        <td>
                            <img src="/Catalog/Images/<%#:Item.ImagePath %>" style="border:solid; height:300px" alt="<%#:Item.ProductName %>"/>
                        </td>
                        <td>&nbsp;</td>  
                        <td style="vertical-align: top; text-align:left;">
                            <b>Description:</b><br /><%#:Item.Description %>
                            <br />
                            <span><b>Price:</b>&nbsp;<%#: String.Format("{0:c}", Item.UnitPrice) %></span>
                            <br />
                            <span><b>Product Number:</b>&nbsp;<%#:Item.ProductID %></span>
                            <br />
                        </td>
                    </tr>
                </table>
            </ItemTemplate>
        </asp:FormView>
    </asp:Content>
    

    此代码使用 FormView 控件显示特定产品详细信息。 此标记使用的方法,如用于在 ProductList.aspx 页中显示数据的方法。 FormView 控件用于一次显示数据源中的一条记录。 使用 FormView 控件时,将创建用于显示和编辑数据绑定值的模板。 这些模板包含用于定义窗体外观和功能的控件、绑定表达式和格式设置。

将前面的标记连接到数据库需要其他代码。

  1. 解决方案资源管理器中,右键单击“ProductDetails.aspx”,然后单击“查看代码”。
    将显示 ProductDetails.aspx.cs 文件。

  2. 将现有代码替换为以下代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using WingtipToys.Models;
    using System.Web.ModelBinding;
    
    namespace WingtipToys
    {
        public partial class ProductDetails : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            public IQueryable<Product> GetProduct([QueryString("productID")] int? productId)
            {
                var _db = new WingtipToys.Models.ProductContext();
                    IQueryable<Product> query = _db.Products;
                    if (productId.HasValue && productId > 0)
                    {
                        query = query.Where(p => p.ProductID == productId);
                    }
                    else
                    {
                        query = null;
                    }
                    return query;
            }
        }
    }
    

此代码检查“”productID查询字符串值。 如果找到有效的查询字符串值,则会显示匹配的产品。 如果找不到查询字符串,或者其值无效,则不会显示任何产品。

运行应用程序

现在,可以运行应用程序来查看基于产品 ID 显示的各个产品。

  1. 在 Visual Studio 中按 F5 运行应用程序。
    浏览器将打开并显示 Default.aspx 页。

  2. 从类别导航菜单中选择“ ”。
    将显示 ProductList.aspx 页。

  3. 从产品列表中选择“ 纸船 ”。 将显示 ProductDetails.aspx 页。

    “纸船产品详细信息”页的屏幕截图。

  4. 关闭浏览器。

其他资源

使用模型绑定和 Web 窗体检索和显示数据

后续步骤

在本教程中,你添加了标记和代码来显示产品和产品详细信息。 你了解了强类型数据控件、模型绑定和值提供程序。 在下一教程中,你将将购物车添加到 Wingtip Toys 示例应用程序。