MVC3 - Asynchronous Pagination

2019-07-31 09:50发布

问题:

I have a list of objects which uses paging in my home > index.cshtml. When a user clicks through each page of objects I only want to refresh that portion of the page and nothing else. How would I accomplish this?

Ideally I want to use Async Methods and ControllerActions...

Controllers > HomeController.cs

public ViewResult Index(int page = 1) {
ProductsListViewModel viewModel = new ProductsListViewModel {
Products = repository.Products
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo {
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.Products.Count()
}
};
return View(viewModel);
}

Home > Index.cshtml:

@model SportsStore.WebUI.Models.ProductsListViewModel
@{
ViewBag.Title = "Products";
}
@foreach (var p in Model.Products) {
<div class="item">
<h3>@p.Name</h3>
@p.Description
<h4>@p.Price.ToString("c")</h4>
</div>
}
<div class="pager">
@Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x}))
</div>

HtmlHelper > PagingHelper.cs

namespace SportsStore.WebUI.HtmlHelpers {
public static class PagingHelpers {
public static MvcHtmlString PageLinks(this HtmlHelper html,
PagingInfo pagingInfo,
Func<int, string> pageUrl) {
StringBuilder result = new StringBuilder();
for (int i = 1; i <= pagingInfo.TotalPages; i++) {
TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString();
if (i == pagingInfo.CurrentPage)
tag.AddCssClass("selected");
result.Append(tag.ToString());
}
return MvcHtmlString.Create(result.ToString());
}
}
}

回答1:

You could use AJAX. The first step is to put the contents that you want to be refreshed into a partial and into its own div:

@model SportsStore.WebUI.Models.ProductsListViewModel
@{
    ViewBag.Title = "Products";
}

<div id="products">
    @Html.Partial("_products", Model.Products)
</div>

<div class="pager">
    @Html.PageLinks(Model.PagingInfo, x => Url.Action("Index", new { page = x }))
</div>

and then of course you will have the corresponding _Products.cshtml partial:

@model IEnumerable<SportsStore.WebUI.Models.ProductViewModel>
@foreach (var p in Model.Products) {
    <div class="item">
        <h3>@p.Name</h3>
        @p.Description
        <h4>@p.Price.ToString("c")</h4>
    </div>
}

and then adapt your controller action so that it is capable of responding to AJAX requests:

public ActionResult Index(int page = 1) 
{
    var viewModel = new ProductsListViewModel 
    {
        Products = repository.Products
            .OrderBy(p => p.ProductID)
            .Skip((page - 1) * PageSize)
            .Take(PageSize),
        PagingInfo = new PagingInfo 
        {
            CurrentPage = page,
            ItemsPerPage = PageSize,
            TotalItems = repository.Products.Count()
        }
    };
    if (Request.IsAjaxRequest())
    {
        return PartialView("_Products", viewModel);
    }

    return View(viewModel);
}

and now all that's left is to AJAXify your pagination anchors. Could be done in a separate javascript file where you could use jQuery to subscribe to the .click() event of them and replace the default action with an AJAX request:

$(function() {
     $('.pager a').click(function() {
         $.ajax({
             url: this.href,
             type: 'GET',
             cache: false,
             success: function(products) {
                 $('#products').html(products);
             }
         });

         // prevent the default redirect
         return false;
     });
});