首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET Repeater 與 ListView 深度解析:從資料呈現到完整 CRUD

     編輯:ASP.NET 基礎

一、Repeater:輕量級唯讀資料呈現

特點:無預設 HTML 結構、無 ViewState (若不啟用)、效能最佳、完全由模板控制輸出。適合:前台清單、導覽列、簡單報表。

核心模板

模板用途備註
HeaderTemplate表頭/清單開頭渲染一次
ItemTemplate每一筆資料對應 foreach 迴圈主體
AlternatingItemTemplate隔行樣式若無則沿用 ItemTemplate
SeparatorTemplate項目間分隔如 <hr/>、<tr class="sep">
FooterTemplate表尾/清單結尾渲染一次

完整 Repeater 範例 (含刪除按鈕)


<asp:ObjectDataSource ID="ods" runat="server"
    TypeName="BLL.ClassService"
    SelectMethod="GetClasses"
    DeleteMethod="DeleteClass">
    <DeleteParameters>
        <asp:Parameter Name="classId" Type="Int32" />
    </DeleteParameters>
</asp:ObjectDataSource>

<table id="tbList" class="table">
    <asp:Repeater ID="rptClass" runat="server" DataSourceID="ods"
        OnItemCommand="rptClass_ItemCommand">
        <HeaderTemplate>
            <thead><tr><th>ID</th><th>名稱</th><th>人數</th><th>圖片</th><th>操作</th></tr></thead><tbody>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td><%# Eval("ClassId") %></td>
                <td><asp:TextBox runat="server" Text='<%# Eval("ClassName") %>' ReadOnly="true" /></td>
                <td><%# Eval("StudentCount") %></td>
                <td>
                    <asp:Image runat="server" ImageUrl='<%# "images/" + Eval("ImageUrl") %>' Width="80" />
                </td>
                <td>
                    <asp:LinkButton runat="server" CommandName="Delete" 
                        CommandArgument='<%# Eval("ClassId") %>' 
                        OnClientClick="return confirm('確定刪除?');">刪除</asp:LinkButton>
                </td>
            </tr>
        </ItemTemplate>
        <AlternatingItemTemplate>
            <tr class="alt-row">
                <td><%# Eval("ClassId") %></td>
                <td><asp:TextBox runat="server" Text='<%# Eval("ClassName") %>' ReadOnly="true" /></td>
                <td><%# Eval("StudentCount") %></td>
                <td><asp:Image runat="server" ImageUrl='<%# "images/" + Eval("ImageUrl") %>' Width="80" /></td>
                <td>
                    <asp:LinkButton runat="server" CommandName="Delete" 
                        CommandArgument='<%# Eval("ClassId") %>' 
                        OnClientClick="return confirm('確定刪除?');">刪除</asp:LinkButton>
                </td>
            </tr>
        </AlternatingItemTemplate>
        <SeparatorTemplate><tr><td colspan="5"><hr/></td></tr></SeparatorTemplate>
        <FooterTemplate></tbody><tfoot><tr><td colspan="5">資料結束</td></tr></tfoot></FooterTemplate>
    </asp:Repeater>
</table>

後端處理 ItemCommand


protected void rptClass_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        int classId = Convert.ToInt32(e.CommandArgument);
        if (new BLL.ClassService().DeleteClass(classId))
        {
            rptClass.DataBind(); // 重新繫結更新畫面
            // 或 ScriptManager.RegisterStartupScript(this, GetType(), "", "alert('刪除成功');", true);
        }
    }
}

二、ListView:功能完整的 CRUD 控制項

ListView = Repeater + 編輯/插入/刪除/分頁/選取 模板整合。Visual Studio 智慧標籤「設定 ListView」可自動產生所有模板。

關鍵模板對照

模板對應功能必要條件
LayoutTemplate整體版面 (含表頭/表尾)必須包含 ID="itemPlaceholder" 的容器 (Panel/PlaceHolder/tr)
ItemTemplate一般資料列—
AlternatingItemTemplate隔行樣式—
EditItemTemplate編輯模式列CommandName="Edit"/"Update"/"Cancel"
InsertItemTemplate新增模式列InsertItemPosition="FirstItem/LastItem"
SelectedItemTemplate選取列樣式CommandName="Select"
EmptyDataTemplate無資料時顯示—

高效分頁:核心原則「只取當頁資料」

預設 EnablePaging="true" 會撈全表再切頁,大數據效能極差。正確做法:

  1. ObjectDataSource 設定 EnablePaging="true"、SelectCountMethod、MaximumRowsParameterName、StartRowIndexParameterName。
  2. BLL/DAL 提供 GetPageList(pageSize, startRowIndex) 與 GetTotalCount()。
  3. SQL 使用 ROW_NUMBER() OVER (ORDER BY ...) 分頁查詢 (SQL Server 2012+ 可用 OFFSET/FETCH)。

ObjectDataSource 分頁設定範例


<asp:ObjectDataSource ID="ods" runat="server"
    TypeName="BLL.ClassService"
    SelectMethod="GetPageList"
    SelectCountMethod="GetTotalCount"
    EnablePaging="true"
    MaximumRowsParameterName="pageSize"
    StartRowIndexParameterName="startRowIndex"
    DeleteMethod="DeleteClass"
    UpdateMethod="UpdateClass"
    InsertMethod="AddClass"
    DataObjectTypeName="MODEL.ClassInfo">
</asp:ObjectDataSource>

BLL 分頁方法簽章


public List GetPageList(int pageSize, int startRowIndex)
{
    return new DAL.ClassRepository().GetPageList(pageSize, startRowIndex);
}

public int GetTotalCount()
{
    return new DAL.ClassRepository().GetTotalCount();
}

DataPager 控制項 (獨立於 ListView)


<asp:DataPager ID="dpClass" runat="server" PagedControlID="lvClass" PageSize="10">
    <Fields>
        <asp:NextPreviousPagerField FirstPageText="首頁" LastPageText="尾頁" 
            NextPageText="下一頁" PreviousPageText="上一頁" ButtonType="Button" />
        <asp:NumericPagerField ButtonCount="5" />
    </Fields>
</asp:DataPager>

三、Repeater vs ListView 選型指南

需求推薦控制項理由
唯讀清單、極致效能、自訂 HTMLRepeater最輕量、無 ViewState 壓力
需內建編輯/新增/刪除/分頁/選取ListView模板完整、聲明式 CRUD
簡單表格、需雙向繫結、自動欄產生GridView開發最快、但 HTML 膨脹
單筆資料詳細檢視/編輯DetailsView / FormView單筆導向

四、現代化建議

新專案建議採用 WebAPI + 前端框架 (Vue/React/Blazor),後端只回傳 JSON,前端負責渲染與互動,徹底解決 ViewState、PostBack、控制項生命週期等傳統 WebForms 痛點。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved