顯示資料項目和詳細資料

作者 :Erik Reitan

本教學課程系列會教導您使用 ASP.NET 4.7 和 Microsoft Visual Studio 2017 建置 ASP.NET Web Forms應用程式的基本概念。

在本教學課程中,您將瞭解如何使用 ASP.NET Web Forms 和 Entity Framework Code First 來顯示資料項目和資料項目詳細資料。 本教學課程是以先前的「UI 和導覽」教學課程為基礎,作為 Wingtip Toy Store 教學課程系列的一部分。 完成本教學課程之後,您會在 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 Form應用程式中所有一般使用者輸入來源的值提供者和對應屬性,例如查詢字串、Cookie、表單值、控制項、檢視狀態、會話狀態和配置檔案屬性。 您也可以撰寫自訂值提供者。

執行應用程式

立即執行應用程式,以檢視所有產品或類別的產品。

  1. 在 Visual Studio 中按 F5 以執行應用程式。
    瀏覽器隨即開啟,並顯示 Default.aspx 頁面。

  2. 從產品類別導覽功能表中選取 [汽車 ]。
    ProductList.aspx頁面只會顯示Cars類別產品。 稍後在本教學課程中,您將顯示產品詳細資料。

    顯示資料項目和詳細資料 - Cars

  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 」 查詢字串值。 如果找到有效的查詢字串值,則會顯示相符的產品。 如果找不到查詢字串,或其值無效,則不會顯示任何產品。

執行應用程式

現在您可以執行應用程式,以查看根據產品識別碼顯示的個別產品。

  1. 在 Visual Studio 中按 F5 以執行應用程式。
    瀏覽器隨即開啟,並顯示 Default.aspx 頁面。

  2. 從類別導覽功能表中選取 [ ]。
    [ ProductList.aspx ] 頁面隨即顯示。

  3. 從產品清單中選取 [紙張船 ]。 ProductDetails.aspx頁面隨即顯示。

    [紙張船產品詳細資料] 頁面的螢幕擷取畫面。

  4. 關閉瀏覽器。

其他資源

使用模型系結和 Web 表單擷取和顯示資料

下一步

在本教學課程中,您已新增標記和程式碼來顯示產品和產品詳細資料。 您已瞭解強型別資料控制項、模型系結和值提供者。 在下一個教學課程中,您會將購物車新增至 Wingtip Toys 範例應用程式。