ASP.NETMVC 分頁

来源:https://www.cnblogs.com/daran/archive/2019/04/01/10639034.html
-Advertisement-
Play Games

<div class="text-center"> <span style="display:inline-block; position:relative;top:-30px;">共 @Model.TotalPageCount 頁 @Model.TotalItemCount 條記錄,當前為第 @M ...


<div class="text-center">
    <span style="display:inline-block;  position:relative;top:-30px;">共 @Model.TotalPageCount 頁 @Model.TotalItemCount 條記錄,當前為第 @Model.CurrentPageIndex 頁</span>
    @Ajax.Pager(Model, new PagerOptions
    {
        /*
         * 設置分頁顯示的樣式
         */
        FirstPageText = "首頁",
        LastPageText = "最後一頁",
        NextPageText = "下一頁",
        PrevPageText = "上一頁",
        PageIndexParameterName = "PageId",
        ContainerTagName = "ul",
        CssClass = "pagination",
        CurrentPagerItemTemplate = "<li class=\"active\"><a href=\"#\">{0}</a></li>",
        DisabledPagerItemTemplate = "<li class=\"disabled\"><a>{0}</a></li>",
        PagerItemTemplate = "<li>{0}</li>"
    },
        new MvcAjaxOptions
        {
            HttpMethod = "post",
            UpdateTargetId = "partList",//更新數據的標簽ID
            DataFormId = "form0"       //分頁對應的條件搜索表單ID
        })
</div>

這是前臺頁面,直接複製到前臺最下麵即可!

 

 

 

 

/* MvcPager source code
This file is part of MvcPager.
Copyright 2009-2015 Webdiyer(http://en.webdiyer.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/ 'use strict';
var Webdiyer = Webdiyer || {};
Webdiyer.MvcPagers = [];
Webdiyer.MvcPagers.getById = function (id) {
    for (var i = 0; i <= this.length; i++) {
        if (typeof this[i] !== "undefined" && this[i].id === id) {
            return this[i];
        }
    }
    return null;
};
Webdiyer.__ajaxPages = {}; //Ajax page parameters, preventing multiple MvcPager with same UrlPageIndexName trigger multiple http requests Webdiyer.MvcPager = function (wrapper) {
    this.wrapper = wrapper;
}; Webdiyer.MvcPager.prototype = {
    wrapper: null,
    id: null,
    urlFormat: null,
    pageIndexName: null,
    updateTarget: null,
    onBegin: null,
    onComplete: null,
    onFailure: null,
    onSuccess: null,
    httpMethod: null,
    confirm: null,
    loadingElementId: null,
    loadingDuration: 0,
    partialLoading: null,
    currentPageIndex: null,
    dataFormId: null,
    allowCache: true,
    enableHistorySupport: null,
    //autoSubmitForm: null,
    searchCriteria: null,
    pageCount: null,
    invalidPageErrMsg: null,
    outOfRangeErrMsg: null,
    firstPageUrl: null,
    pageIndexBox: null,
    goToButton: null,
    maxPageIndexItems: 20,
    isAjaxPager: null,
    onError: null,
    isFirstLoading: true,
    allowReload: false, //used by search form to check if reload is needed even current page index is not changed
    init: function () {
        var wrapper = $(this.wrapper);
        var newPageIndex = 1;
        var initialPageIndex; //value of the page index when page is loaded first time, if go back to this page we need to load the correct data by checking this value(it's not necessarily to be 1)
        this.id = wrapper.attr("id");
        this.isAjaxPager = wrapper.data("ajax") || false;
        this.pageCount = wrapper.data("pagecount");
        this.invalidPageErrMsg = wrapper.data("invalidpageerrmsg");
        this.outOfRangeErrMsg = wrapper.data("outrangeerrmsg");
        this.firstPageUrl = wrapper.data("firstpage");
        this.urlFormat = wrapper.data("urlformat");
        this.pageIndexName = wrapper.data("pageparameter");
        this.currentPageIndex = wrapper.data("currentpage") || 1;
        this.pageIndexBox = wrapper.data("pageindexbox");
        this.goToButton = wrapper.data("gotobutton");
        this.maxPageIndexItems = wrapper.data("maxitems") || 20;
        this.onError = wrapper.data("onerror") || "alert(errMsg)";
        var context = this;
        if (this.isAjaxPager) {
            this.updateTarget = wrapper.data("ajax-update");
            this.onBegin = wrapper.data("ajax-begin");
            this.onComplete = wrapper.data("ajax-complete");
            this.onFailure = wrapper.data("ajax-failure");
            this.onSuccess = wrapper.data("ajax-success");
            this.confirm = wrapper.data("ajax-confirm") || undefined;
            this.httpMethod = wrapper.data("ajax-method") || "GET";
            this.loadingElementId = wrapper.data("ajax-loading") || undefined;
            this.dataFormId = wrapper.data("ajax-dataformid") || undefined;
            this.allowCache = wrapper.data("ajax-allowcache") || true;
            var history = wrapper.data("ajax-enablehistorysupport");
            this.enableHistorySupport = (typeof history === "undefined" ? true : history);
            //this.autoSubmitForm = wrapper.data("ajax-autosubmitform") || false;
            this.loadingDuration = wrapper.data("ajax-loading-duration") || 0;
            this.partialLoading = wrapper.data("ajax-partialloading") || false;
            initialPageIndex = this.currentPageIndex;
            var pagerSelector = "[data-pagerid='Webdiyer.MvcPager']";
            var hashIndex = this.__getPageIndex(this.pageIndexName);
            if (hashIndex !== this.currentPageIndex && hashIndex > 0)
            { this.__ajax(hashIndex, { type: this.httpMethod, data: [] }); }
            if (typeof this.dataFormId !== "undefined") {
                var isAjaxForm = $(context.dataFormId).data("ajax") || false;
                $(context.dataFormId).submit(function (event) {
                    context.searchCriteria = $(context.dataFormId).serializeArray();
                    if (isAjaxForm) {
                        if (context.currentPageIndex !== 1) {
                            context.currentPageIndex = 1;
                            if (context.enableHistorySupport) {
                                context.__setPageIndex(context.pageIndexName, -1); //prevent reloading triggered by hashchange event
                                context.allowReload = true;
                            } else {
                                context.__ajax(1, { type: context.httpMethod, data: [] });
                            }
                        } else {
                            if (typeof Webdiyer.__ajaxPages[context.pageIndexName] === "undefined")
                            { context.allowReload = true; }
                        }
                    } else {
                        if (typeof Webdiyer.__ajaxPages[context.pageIndexName] === "undefined")
                        { context.allowReload = true; }
                        if (context.currentPageIndex === 1) {
                            context.__ajax(1, { type: context.httpMethod, data: [] });
                        } else {
                            if (context.enableHistorySupport) {
                                context.__setPageIndex(context.pageIndexName, 1);
                            } else {
                                context.__ajax(1, { type: context.httpMethod, data: [] });
                            }
                            context.currentPageIndex = 1;
                        } context.allowReload = true;
                        event.preventDefault();
                    }
                });
            }
            if (this.enableHistorySupport) {
                this.__initHashChange(initialPageIndex);
            }
            //pagination items
            $(this.updateTarget).on("click", pagerSelector + " a[data-pageindex]", function (e) {
                newPageIndex = $(this).data("pageindex");
                e.preventDefault();
                if (context.enableHistorySupport) {
                    context.__setPageIndex(context.pageIndexName, newPageIndex);
                } else {
                    context.__ajax(newPageIndex, { type: context.httpMethod, data: [] });
                }
            });
        }
        //page index box
        this.__bindPageIndexBox();
        return this;
    },
    __bindPageIndexBox: function () {
        var context = this;
        if (context.isAjaxPager) {
            if ($.trim(context.pageIndexBox) !== "") {
                if ($(context.updateTarget).find(context.pageIndexBox).length > 0) {
                    //page index box is inside of update target area
                    //check if page index box is dropdownlist and fill it with page indices
                    context.__fillPageIndexBox();
                    if ($(context.pageIndexBox).is('input:text')) {
                        $(context.pageIndexBox).val(context.currentPageIndex);
                        $(context.updateTarget).on("keydown", context.pageIndexBox, function () {
                            context.__validateInput(event);
                        });
                    }
                    if ($.trim(context.goToButton) !== "") {
                        $(context.updateTarget).on("click", context.goToButton, function () {
                            var newPageIndex = $(context.pageIndexBox).val();
                            context.goToPage(newPageIndex);
                        });
                    } else {
                        $(context.updateTarget).on("change", context.pageIndexBox, function () {
                            var newPageIndex = $(context.pageIndexBox).val();
                            context.goToPage(newPageIndex);
                        });
                    }
                } else {
                    //page index box is outside of update target area
                    context.__bindBoxEvents();
                }
            }
        } else {
            //page index box
            if ($.trim(context.pageIndexBox) !== "") {
                context.__bindBoxEvents();
            }
        }
    },
    __bindBoxEvents: function () {
        var context = this;
        context.__fillPageIndexBox();
        if ($(context.pageIndexBox).is('input:text')) {
            $(context.pageIndexBox).val(context.currentPageIndex);
            $(context.pageIndexBox).keydown(function () {
                context.__validateInput(event);
            });
        }
        if ($.trim(context.goToButton) !== "") {
            $(context.goToButton).click(function () {
                var newPageIndex = $(context.pageIndexBox).val();
                context.goToPage(newPageIndex);
            });
        } else {
            $(context.pageIndexBox).change(function () {
                var newPageIndex = $(context.pageIndexBox).val();
                context.goToPage(newPageIndex);
            });
        }
    },
    __fillPageIndexBox: function () {
        var se = $(this.pageIndexBox);
        if (se.prop('type') === 'select-one') {
            se.empty();
            var startIndex = this.currentPageIndex - (this.maxPageIndexItems / 2);
            if (startIndex + this.maxPageIndexItems > this.pageCount)
            { startIndex = this.pageCount + 1 - this.maxPageIndexItems; }
            if (startIndex < 1)
            { startIndex = 1; }
            var endIndex = startIndex + this.maxPageIndexItems - 1;
            if (endIndex > this.pageCount)
            { endIndex = this.pageCount; }
            for (var i = startIndex; i <= endIndex; i++) {
                se.append('<option value="' + i + '">' + i + '</option>');
            }
        }
        se.val(this.currentPageIndex);
    },
    __initHashChange: function (initialPageIndex) {
        var context = this;
        var docMode = document.documentMode;
        if ("onhashchange" in window &&
        (docMode === undefined || docMode > 7)) //IE compatable mode
        {
            $(window).bind("hashchange", function () {
                var pageIndex = context.__getPageIndex(context.pageIndexName);
                if (pageIndex === 0)
                { pageIndex = initialPageIndex; } //initial page index in url without hash value,eg. when go back from articles/list/3#id=2 to articles/list/3 initialPageIndex will be 3;
                context.__ajax(pageIndex, { type: context.httpMethod, data: [] });
            });
        } else {
            var currentHash = window.location.hash;
            setInterval(function () {
                var pageIndex = context.__getPageIndex(context.pageIndexName);
                if (window.location.hash !== currentHash) {
                    currentHash = window.location.hash;
                    if (pageIndex === 0)
                    { pageIndex = initialPageIndex; }
                    context.__ajax(pageIndex, { type: context.httpMethod, data: [] });
                }
            }, 200);
        }
    },
    __getPageIndex: function (pname) {
        var hash = window.location.hash.substring(1);
        if ($.trim(hash) !== "") {
            var harr = hash.split('&');
            for (var i = 0; i < harr.length; i++) {
                var hval = harr[i].split("=");
                if (hval[0].toString().toLowerCase() === pname.toString().toLowerCase()) {
                    return parseInt(hval[1]) || 1;
                }
            }
        }
        return 0;
    },
    __setPageIndex: function (pname, pindex) {
        var hash = window.location.hash.substring(1);
        if ($.trim(hash) === "")
        { window.location.hash = pname + "=" + pindex; }
        else {
            var r = new RegExp(pname + "=[^&]*", 'i');
            if (!r.test(hash))
            { window.location.hash += "&" + pname + "=" + pindex; }
            else {
                var index = hash.replace(r, pname + "=" + pindex);
                window.location.hash = index;
            }
        }
    },
    goToPage: function (pageIndex) {
        var r = new RegExp("^\\s*(\\d+)\\s*$");
        if (!r.test(pageIndex)) {
            this.__getFunction(this.onError, ["errType", "errMsg"]).apply(this, [0, this.invalidPageErrMsg]);
            return;
        } else if (RegExp.$1 < 1 || RegExp.$1 > this.pageCount) {
            this.__getFunction(this.onError, ["errType", "errMsg"]).apply(this, [1, this.outOfRangeErrMsg]);
            return;
        }
        if (this.isAjaxPager) {
            if (this.enableHistorySupport) {
                this.__setPageIndex(this.pageIndexName, pageIndex);
            } else {
                this.__ajax(pageIndex, { type: this.httpMethod, data: [] });
            }
        } else {
            if (typeof this.firstPageUrl !== "undefined" && this.firstPageUrl !== false && parseInt(pageIndex) === 1)
            { window.self.location.href = this.firstPageUrl; }
            else
            { window.self.location.href = decodeURI(this.urlFormat).replace("__" + this.pageIndexName + "__", pageIndex); }
        }
    },
    __ajax: function (index, options) {
        var context = this;
        if (typeof Webdiyer.__ajaxPages[context.pageIndexName] === "undefined" || Webdiyer.__ajaxPages[context.pageIndexName] !== index || context.allowReload) { //prevent duplicate ajax requests
            if (index === -1 || (index === 0 && context.isFirstLoading) || (index === context.currentPageIndex && !context.allowReload)) {
                return;
            }
            if (context.confirm && !(window.confirm(context.confirm))) {
                return;
            }
            $.extend(options, {
                url: this.urlFormat.replace("__" + context.pageIndexName + "__", index),
                cache: this.allowCache,
                beforeSend: function (xhr) {
                    var formMethod = options.type.toUpperCase();
                    if (!(formMethod === "GET" || formMethod === "POST")) {
                        xhr.setRequestHeader("X-HTTP-Method-Override", formMethod);
                    }
                    var result = context.__getFunction(context.onBegin, ["xhr"]).apply(this, arguments);
                    if (result !== false && typeof context.loadingElementId !== "undefined") {
                        $(context.loadingElementId).show(context.loadingDuration);
                    }
                    return result; //Ajax request will be cancelled if return false
                },
                complete: function () {
                    if (typeof context.loadingElementId !== "undefined") {
                        $(context.loadingElementId).hide(context.loadingDuration);
                    }
                    context.__fillPageIndexBox();
                    context.__getFunction(context.onComplete, ["xhr", "status"]).apply(this, arguments);
                },
                success: function (data) {
                    if (context.partialLoading)
                    { $(context.updateTarget).html($(context.updateTarget, data).html()); }
                    else
                    { $(context.updateTarget).html(data); }
                    context.currentPageIndex = index;
                    context.isFirstLoading = false;
                    context.__getFunction(context.onSuccess, ["data", "status", "xhr"]).apply(this, arguments);
                },
                error: context.__getFunction(context.onFailure, ["xhr", "status", "error"])
            });
            if (typeof context.dataFormId !== "undefined") {
                context.__pushData(options.data, context.searchCriteria);
            }
            options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });
            var method = options.type.toUpperCase();
            if (!(method === "GET" || method === "POST")) {
                options.type = "POST";
                options.data.push({ name: "X-HTTP-Method-Override", value: method });
            }
            $.ajax(options);
            Webdiyer.__ajaxPages[context.pageIndexName] = index;
        }
    },
    __pushData: function (dataArr, dataToPush) {
        if (dataToPush !== null && typeof dataToPush !== "undefined") {
            for (var i = 0; i < dataToPush.length; i++) {
                dataArr.push({ name: dataToPush[i].name, value: dataToPush[i].value });
            }
        }
    },
    __getFunction: function (code, argNames) {
        var fn = window, parts = (code || "").split(".");
        while (fn && parts.length) {
            fn = fn[parts.shift()];
        }
        if (typeof (fn) === "function") {
            return fn;
        } //onSuccess="functionName"
        if ($.trim(code).toLowerCase().indexOf("function") === 0) {
            /*jslint evil: true */
            return new Function("return (" + code + ").apply(this,arguments);");
        } //onSuccess="function(data){alert(data);}"
        argNames.push(code);
        try {
            return Function.constructor.apply(null, argNames); //onSuccess="alert('hello');return false;"
        } catch (e) {
            alert("Error:\r\n" + code + "\r\n is not a valid callback function");
        }
    },
    __validateInput: function (e) {
        var kc;
        if (window.event) {
            kc = e.keyCode;
        }
        else if (e.which) {
            kc = e.which;
        }
        var valideKeys = [8, 37, 39, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
        if (kc !== null && valideKeys.indexOf(kc) < 0) {
            if (e.preventDefault) {
                e.preventDefault();
            }
            else {
                event.returnValue = false;
            }
        }
    }
};
(function ($) {
    $.fn.initMvcPagers = function () {
        return this.each(function () {
            Webdiyer.MvcPagers.push(new Webdiyer.MvcPager(this).init());
        });
    };
})(jQuery);
$(function () { $("[data-pagerid='Webdiyer.MvcPager']").initMvcPagers(); }); 這是JS代碼 封裝起來,頁面直接引用!           還要引用一個程式集,在我博客裡面,這裡不能放,自己去看看吧!
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Leetcode(2) 記:這幾天內心十分焦慮,研究生的日子一天天過去,感覺毫無收穫,每天刷個題來壓壓驚. 2.Add Two Number · 錯誤示例 · 思路 寫兩個函數將一個數從List轉化為int, 相加後再從int轉化為List返回. · 偽代碼: 1.構造兩個函數分別代表: 一個數字從 ...
  • ssm客戶管理系統 註意:本文是在我的上一篇文章 https://www.cnblogs.com/peter-hao/p/ssm.html的基礎上開發 1 需求 1.1 添加客戶 客戶填寫信息,提交,將信息保存到資料庫中。 1.2 刪除客戶 在每條查詢出來的客戶信息設置刪除操作,點擊即可刪除。更新數 ...
  • /** * 給定一個字元串,統計每個字元出現的次數。 如:abdaewrwqask435a1aasd */public class ReplaceString { static int length; public static void countString(String s) { while ...
  • 見過的最詳細的ArrayList的源碼分析了,分析得很透徹。比如,c.toArray()一定返回Object[]類型嗎?elementData聲明為transient,那它到底是怎麼序列化的呢?遠遠不止這些…… ...
  • spring cloud gateway負載普通web項目 對於普通的web項目,也是可以通過 進行負載的,只是無法通過服務發現。 背景 不知道各位道友有沒有使用過 "帆軟" ,帆軟是國內一款報表工具,這裡不做過多介紹。 它是通過war包部署到 ,預設是單台服務。如果想做集群,需要配置 ,帆軟會將當 ...
  • 在Sqlserver資料庫管理軟體中,Sqlserver對系統記憶體的管理原則是:按需分配,並且分配完成後為了查詢有更好的性能,並不會立即自動釋放記憶體,數據取出後,還會一直占用著記憶體,所以在Sqlserver服務啟動後,你會發現sqlserver占用的記憶體越來越大,直到稍微小於機器記憶體一定值。其實我們 ...
  • 和WPF數字滾動抽獎有區別,WPF數字滾動抽獎是隨機的,而這裡是確定的。 為了系統演示,這個效果通宵加班寫了整整6個小時,中間就上了次廁所。 有點小BUG改天再改。 代碼: RollingNumberItemCtrl.xaml代碼: <UserControl x:Class="SunCreate.C ...
  • 語言的設計,真的是挺有意思的。第一次看這個代碼[1]時,旁人隨口了一句“哇,好多實心句號”。 當時馬上一個想法是——怎麼實現的?返回了對象,然後再調用方法?然後就放下了,後來發現,這個是真值得說一說的。 1. 神奇的鏈接(chaining) 1.1 拓展方法 想了很久該怎麼引入話題,或者這樣說,像這 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...