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

ASP.NET MVC 2 右鍵選單與簡易分頁實作

     編輯:ASP.NET 基礎

右鍵選單:jQuery contextMenu 外掛

1. 引用腳本與樣式

<script src="~/Scripts/jquery.contextmenu.js"></script>
<link href="~/Content/contextmenu.css" rel="stylesheet" />

2. 定義選單 HTML

<div class="contextMenu" id="myMenu1">
    <ul>
        <li id="detail"><img src="/Content/detail.ico" />明細</li>
        <li id="new"><img src="/Content/new.ico" />新增</li>
        <li id="delete"><img src="/Content/delete.ico" />刪除</li>
        <li id="modify"><img src="/Content/modify.ico" />修改</li>
    </ul>
</div>

3. 綁定目標元素

<td class="showContext" id="<%= item.ProductID %>">
    <%: item.ProductName %>
</td>

4. 啟用並處理點擊

$(function () {
    $('td.showContext').contextMenu('myMenu1', {
        bindings: {
            'detail': function (t) { location.href = '/Products/Detail/' + t.id; },
            'new':    function (t) { location.href = '/Products/Detail/' + t.id; },
            'delete': function (t) { if (confirm('確定刪除?')) location.href = '/Products/Delete/' + t.id; },
            'modify': function (t) { location.href = '/Products/Edit/' + t.id; }
        }
    });
});

簡易分頁:HtmlHelper 擴充方法

擴充方法實作

public static class PagingExtensions
{
    public static string Pager(this HtmlHelper helper, int currentPage, int pageSize, int totalRecords, string urlPrefix)
    {
        var sb = new StringBuilder();
        int totalPages = (int)Math.Ceiling((double)totalRecords / pageSize);
        int start = Math.Max(1, currentPage - 2);
        int end = Math.Min(totalPages, currentPage + 2);

        if (currentPage > 1)
            sb.AppendFormat("<a href='{0}/{1}'>上一頁</a> ", urlPrefix, currentPage - 1);

        for (int i = start; i <= end; i++)
        {
            if (i == currentPage)
                sb.AppendFormat("<span class='current'>{0}</span> ", i);
            else
                sb.AppendFormat("<a href='{0}/{1}'>{1}</a> ", urlPrefix, i);
        }

        if (currentPage < totalPages)
            sb.AppendFormat("<a href='{0}/{1}'>下一頁</a>", urlPrefix, currentPage + 1);

        return sb.ToString();
    }
}

View 中使用

<div class="pager">
    <%= Html.Pager(Model.CurrentPage, Model.PageSize, Model.TotalItems, "/Products/List") %>
</div>

執行效果

右鍵選單效果 分頁效果

現代化替代方案

  • 右鍵選單:contextmenu.js、tippy.js、Headless UI Menu
  • 分頁:X.PagedList、TagHelper (ASP.NET Core)、Bootstrap Pagination

MVC 2 時代的經典做法,理解原理後易於遷移至現代框架。

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