ajax分页asp.net mvc

时间:2012-10-25 20:23:49

标签: asp.net asp.net-mvc

我知道如何将ajax分页连接到asp.net mvc中的网格或webgrid。但是如何使用自定义分页为表格网格之外的另一种格式的大型数据集完成ajax分页。

甚至可以使用mvc helper或mvc.pagedlist吗?

我曾经是一个webforms人员,很容易连接一个listview,你可以使用div来创建你想要的单个项目的任何布局,然后你可以连接一个数据页并将它包装在一个更新面板中

基本上我想要一个可以通过ajax浏览的项目列表,但是有了大数据集我可以通过jquery下拉所有项目和页面,我需要在服务器端进行自定义分页并且只返回特定页面的项目。

3 个答案:

答案 0 :(得分:2)

通过重用部分视图和一些ajax,可以在MVC中轻松完成。

将此模型作为属性添加到页面的ViewModel以处理分页:

namespace Models.ViewModels
{    
    [Serializable()]
    public class PagingInfoViewModel
    {

        public int TotalItems { get; set; }
        public int ResultsPerPage { get; set; }
        public int CurrentPage { get; set; }
        public int TotalPages {
            get { return Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(this.TotalItems) / this.ResultsPerPage)); }
        }
        public string LinkTextShowMore { get; set; }
        public string LinkTextShowingAll { get; set; }
        /// <summary>
        /// Paging url used by the jQuery Ajax function
        /// </summary>
        public string UrlGetMore { get; set; }

        public PagingInfoViewModel(string linkTextShowMore, string linkTextShowingAll, int resultsPerPage)
        {
            this.LinkTextShowMore = linkTextShowMore;
            this.LinkTextShowingAll = linkTextShowingAll;
            this.ResultsPerPage = resultsPerPage;
        }
    }
}

将以下代码添加到局部视图中以处理分页:

    //Start Pagination
    //determine the value for the X for "Showing X of Y"
    {
        int currentTotal = 0;
        if ((Model.PagingInfo.CurrentPage * Model.PagingInfo.ResultsPerPage) < Model.PagingInfo.TotalItems) {
            //the current max item we are displaying is less than the total number of policies
            //display the current max item index\
            currentTotal = Model.PagingInfo.CurrentPage * Model.PagingInfo.ResultsPerPage;
        } else {
            //the current is greater than the total number of policies
            //display the total number of policies
            currentTotal = Model.PagingInfo.TotalItems;
        }
        if (Model.PagingInfo.TotalPages == 0 || Model.PagingInfo.CurrentPage == Model.PagingInfo.TotalPages) 
{
        @<li>
            <h3>@Model.PagingInfo.LinkTextShowingAll</h3>
            <p><strong>Showing @currentTotal Of @Model.PagingInfo.TotalItems</strong></p>
        </li>

        } else {
        @<li id="GetMore">
                <a href="#" id="lnkGetMore">
                    <h3>@Model.PagingInfo.LinkTextShowMore</h3>
                    <p><strong>Showing @(currentTotal) Of @Model.PagingInfo.TotalItems</strong></p>
                </a> 
        </li>
        @<script type="text/javascript"  lang="javascript">
             $('#lnkGetMore').click(function () {
                 $.ajax({
                     url: "@Model.PagingInfo.UrlGetMore",
                     success: function (data) {
                         $('#ProducerList li:last').remove();
                         $('#ProducerList').append(data);
                         $('#ProducerList').listview('refresh');
                     }
                 });
                 return false;
             });
        </script>
        }
    }

现在,最后的javascript专门用于使用ul和li的UI,但可以根据需要轻松定制。

将模型传递给视图时,后端会设置UrlGetMore属性。我确信有一种更优雅的方式来做到这一点。这是我使用的代码:

//build paging url used by the jQuery Ajax function
view.PagingInfo.UrlGetMore == Url.RouteUrl("RouteItemList", new { page = view.PagingInfo.CurrentPage + 1 })

最后,这是处理初始视图和后续部分视图(ajax调用)的操作

public ActionResult List(UserModel user, ViewModel view, int page = 1)
{

    IQueryable<model> models = this.RetrieveModels(user, view);

    if ((models != null) && models.Count > 0) {
        view.PagingInfo.CurrentPage = page;
        view.PagingInfo.ResultsPerPage = user.Preferences.ResultsPerPage;
        view.PagingInfo.TotalItems = models.Count;

        view.items = models.Skip((page - 1) * user.Preferences.ResultsPerPage).Take(user.Preferences.ResultsPerPage).ToList();

        //build paging url used by the jQuery Ajax function
        view.PagingInfo.UrlGetMore = Url.RouteUrl("RouteList", new { page = view.PagingInfo.CurrentPage + 1 });
    }


    if (page == 1) {
        return View(view);
    } else {
        return PartialView("ListPartial", view);
    }

}

HTH。

答案 1 :(得分:2)

您可以创建简单的HtmlHelper simillar:

public static class HtmlPaginHelper
{        
    public static MvcHtmlString PagerNoLastPage(this AjaxHelper ajaxHelper,
                                                int page,
                                                int pageSize,
                                                bool isLastPage,
                                                Func<int, string> pageUrl,
                                                Func<int, AjaxOptions> pageAjaxOptions)
    {
        var result = new StringBuilder();

        var firstPageAnchor = new TagBuilder("a");
        firstPageAnchor.SetInnerText("<<");

        var prevPageAnchor = new TagBuilder("a");
        prevPageAnchor.SetInnerText("<");

        var nextPageAnchor = new TagBuilder("a");
        nextPageAnchor.SetInnerText(">");

        var currentPageText = new TagBuilder("span");
        currentPageText.SetInnerText(string.Format("Page: {0}", page));

        if (page > 1)
        {
            firstPageAnchor.MergeAttribute("href", pageUrl(1));
            firstPageAnchor.MergeAttributes(pageAjaxOptions(1).ToUnobtrusiveHtmlAttributes());

            prevPageAnchor.MergeAttribute("href", pageUrl(page - 1));
            prevPageAnchor.MergeAttributes(pageAjaxOptions(page - 1).ToUnobtrusiveHtmlAttributes());
        }
        if (!isLastPage)
        {
            nextPageAnchor.MergeAttribute("href", pageUrl(page + 1));
            nextPageAnchor.MergeAttributes(pageAjaxOptions(page + 1).ToUnobtrusiveHtmlAttributes());
        }

        result.Append(firstPageAnchor);
        result.Append(prevPageAnchor);
        result.Append(currentPageText);
        result.Append(nextPageAnchor);

        return MvcHtmlString.Create(result.ToString());
    }
}

...然后在你的Razor视图中使用它:

网格结果在这里......

@Ajax.PagerNoLastPage(Model.Query.Page,
                            Model.Query.PageSize,
                            Model.Data.IsLastPage,
                            i => Url.Action("Index", RouteValues(i)),
                            i => new AjaxOptions
                                     {
                                         UpdateTargetId = "content",
                                         InsertionMode = InsertionMode.Replace,
                                         HttpMethod = "GET",
                                         Url = Url.Action("Grid", RouteValues(i))
                                     })

其中RouteValues(i)的定义如下:

@functions {
    private object PageRouteValues(int i)
    {
        return new
                   {
                       payId = Model.Query.PayId,
                       clientCode = Model.Query.ClientCode,
                       fromDate = Model.Query.FromDate,
                       tillDate = Model.Query.TillDate,
                       payNum = Model.Query.PayId,
                       checkNum = Model.Query.CheckNum,
                       payType = Model.Query.PayType,
                       payStatus = Model.Query.PayStatus,
                       page = i,
                       pageSize = Model.Query.PageSize
                   };
    }
}

答案 2 :(得分:1)

  

甚至可以使用mvc helper或mvc.pagedlist吗?

是的,但当然您必须使用服务器端操作协调客户端请求以处理实际的数据分页。从这个意义上说,它不像WebForms那么简单,但它仍然是可能的。

Here's使用PagedList在自己的表中呈现每个返回项目的示例,由水平规则分隔。您应该可以轻松地修改示例中的HTML以生成所需的任何渲染。