欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NETMVC 分页

程序员文章站 2022-07-11 10:33:33
共 @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代码 封装起来,页面直接引用!
 
 
 
 
 
还要引用一个程序集,在我博客里面,这里不能放,自己去看看吧!