Giter Club home page Giter Club logo

mvcpaging's Introduction

The MvcPaging library contains an ASP.NET MVC HTML helper that renders a pager based on given parameters. A live demo can be found at http://demo.taiga.nl/mvcpaging.

Important information for ASP.NET Core users

This library doesn't support ASP.NET Core. Visit https://github.com/joeaudette/cloudscribe.Web.Pagination for the logical successor of this library. Thanks Joe for the effort!

Usage (Razor / pseudo code):

@Html.Pager(pageSize, pageNumber, totalItemCount)

Options are added via the Options method:

@Html.Pager(pageSize, pageNumber, totalItemCount).Options(o => o
	.Action("action")
	.AddRouteValue("q", mySearchQuery)
)

Possible options:

Action(string action)
	Sets an alternative action for the pager that is different from the current action

Action(string action, string controller)
	Sets an alternative action and controller for the pager that is different from the current

AddRouteValue(string name, object value)
	Adds a single route value parameter that is added to page url's

AddRouteValueFor<TProperty>(Expression<Func<TModel, TProperty>> expression)
	Adds a strongly typed route value parameter based on the current model
	(e.g. AddRouteValueFor(m => m.SearchQuery))

RouteValues(object routeValues)
	Adds route value parameters that are added to the page url's

RouteValues(RouteValueDictionary routeValues)
	Adds route value parameters that are added to the page url's

DisplayTemplate(string displayTemplate)
	When set, the internal HTML rendering is bypassed and a DisplayTemplate view with the given
	name is rendered instead. Note that the DisplayTemplate must have a model of type PaginationModel.
	Instead of a template name, it's also possible to specify a complete template path, starting with ~/

MaxNrOfPages(int maxNrOfPages)
	Sets the maximum number of pages to show	

AlwaysAddFirstPageNumber
	By default we don't add the page number for page 1 because it results in canonical links. 
	Use this option to override this behaviour.	

PageRouteValueKey
	Set the page routeValue key for pagination links

DisplayFirstAndLastPage
	Displays first and last navigation pages

DisplayFirstPage
	Displays the first navigation page

DisplayLastPage
	Displays the last navigation page

SetFirstPageText
	Set a custom text for the first page

SetFirstPageTitle
	Set a custom text for title attribute of the first page link

SetLastPageText
	Set a custom text for the last page

SetLastPageTitle
	Set a custom text for title attribute of the last page link
	
SetPreviousPageText
	Set a custom text for the previous page

SetPreviousPageTitle
	Set a custom text for title attribute of the previous page link

SetNextPageText
	Set a custom text for the next page

SetNextPageTitle
	Set a custom text for title attribute of the next page link
	
UseItemCountAsPageCount
	The totalItemCount parameter is (ab)used for the total number of pages
	instead of the total number of items to facilitate backends that return the total number
	of pages instead of the total number of items

HidePreviousAndNextPage
	Don't show the 'previous' and 'next' links and only show the page numbers
	
CustomRouteName
	Indicate that a specific named route must be used when generating page links

HideFirstPageNumber
	Don't show page number 1 and '...' when navigating away

HideLastPageNumber
	Don't show the number of the last page and '...' when the last page is more than
	MaxNumberOfPages

PagedList

The library contains a PagedList class that makes it easy to work with paged data. Use it via an extension method on IEnumerable<> or IList<>:

myList.ToPagedList(pageIndex, pageSize)

with any unpaged list or

myList.ToPagedList(pageIndex, pageSize, totalItemCount)

when the list already only contains the data for the page

Contributing

Contributions via pull requests are great. We use 4 spaces for indentation :-).

mvcpaging's People

Contributors

bryant1410 avatar cce32 avatar chunkily avatar cvrajeesh avatar dsouzaj86 avatar edokan avatar grabmill avatar hmol avatar leebarbara avatar martijnboland avatar meligy avatar nhotalling avatar nicollasricas avatar rafgithub avatar subeax avatar thecloudlesssky avatar thierryx96 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mvcpaging's Issues

Custom template with DisplayTemplate and full path not working

First thank you very much for your nice component :)

In my project i need to specify the full path of my template but when i use a path like :
~/Areas/SiteWeb/Views/Shared/_MyTemplate.cshtml it is not working because in your component in Pager.cs you force the template to be in the Displaytemplates folder like this :
var templatePath = string.Format("DisplayTemplates/{0}", this.pagerOptions.DisplayTemplate);

I suggest to check if this.pagerOptions.DisplayTemplate start with ~ in order to use full path like this for example :

if (!String.IsNullOrEmpty(this.pagerOptions.DisplayTemplate))
{
	var templatePath = String.empty;
	if(this.pagerOptions.DisplayTemplate.StartsWith("~")){
		templatePath = this.pagerOptions.DisplayTemplate;
	}
	else{
		templatePath = string.Format("DisplayTemplates/{0}", this.pagerOptions.DisplayTemplate);
	}
	return htmlHelper.Partial(templatePath, model).ToHtmlString();
}

It will be more flexible for people who have my needs.

Thank you in advance

Not compatible with MVC 3

Hi,

I am stuck with this error, is the library compatible with MVC3 or how do I go around this without upgrading to MVC4?

Error 1 Assembly 'MvcPaging, Version=2.1.2.28, Culture=neutral, PublicKeyToken=null' uses 'System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which has a higher version than referenced assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
c:\packages\MvcPaging.2.1.2\lib\net40\MvcPaging.dll ***

Update Nuget

Hey Taiga, How are you?

Can you update MvcPaging into Nuget with the last modifications?

Thanks!

When using a custom template, there is no way to pass in custom data.

I am trying to build a custom template for paging that includes which records are being displayed and total record count -- something like "Viewing records 51-100 of 721". It would be nice if I could pass in some custom data, maybe a property on the PaginationModel available to the custom template.

Runtime error ArrayTypeMismatchException

runtime error occurred in mvcpaging, it works on the MVC project, but when move to a web form and mvc mixed project, an runtime error occurred.
following is the stack trace

[ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array.]
System.Collections.Generic.List1.set_Item(Int32 index, T value) +24 System.Collections.ObjectModel.Collection1.SetItem(Int32 index, T item) +55
System.Web.Routing.RouteCollection.SetItem(Int32 index, RouteBase item) +58
System.Collections.ObjectModel.Collection1.set_Item(Int32 index, T value) +116 System.Web.Mvc.ControllerContext.get_RequestContext() +25 MvcPaging.Pager.GeneratePageUrl(Int32 pageNumber) +41 MvcPaging.Pager.BuildPaginationModel(Func2 generateUrl) +978
MvcPaging.Pager.ToHtmlString() +82
System.Web.HttpUtility.HtmlEncode(Object value) +38
System.Web.WebPages.WebPageBase.Write(Object value) +68

Weird behaviour when the list have just part of data

Hi.

There is a little bug, it seems, though it appears in special (not very likely to happen) circumstances.

I am using the feature of creating PagedList from List with just part of all data (myList.ToPagedList(pageIndex, pageSize, totalItemCount)). Everything is OK when the count of list elements is equal or less than PageSize (which is quite natural). But suppose the list contains more elements than needed (say, 15 instead of 10). I think we should get PagedList of just first 10 items and drop the excess. But PagedList constructor works differently (when page number > 1).

The problem lies in this piece of code:

        var realTotalPages = (int)Math.Ceiling(realTotalCount / (double)PageSize);

        if (realTotalCount < TotalItemCount && realTotalPages <= PageIndex)
            AddRange(source.Skip((realTotalPages - 1) * PageSize).Take(PageSize));
        else
            AddRange(source.Skip(PageIndex * PageSize).Take(PageSize));

Maybe there is some reason for such a complex if statement, but I don't get it. For what puprose there is a realTotalPages variable? Maybe I am missing something.

Think, I could fix this part, but I'd like to be sure I get everything right.

PageRouteValueKey not working

Hello
I have this:
[Route("genericos-referencias}", Order = 3, Name = "appGenericosReferenciasController.Index.es")]
[Route("{lang}/generic-references}", Order = 4, Name = "appGenericosReferenciasController.Index.en")]
public async Task Index()
..

I want than MVC paging generate this link in every page:
http://localhost:29553/generic-references?page=2

I try set:
.PageRouteValueKey("appGenericosReferenciasController.Index.en")

But always get:
http://localhost:29553/genericos-referencias?page=2

Any mehtod to override base URL of links?
Thanks

Last page calculation is broken

Steps to see this error are:

1) Run MvcPaging.Demo
2) Go to "Paging with a custom page route value key"
3) Click on last page "52" just after "..."
4) You'll see that page 53 appears.

You have my pull-request. Please review it and merge if it's correct.

would you consider an option to pass in total pages instead of total items?

Hi Martijn,

I started working on my own pager for mvc but found yours which looks very nice. One problem for me is that the project I'm working on already has data access methods for returning a page of data, we pass in the page size and current page number and it gives us totalPages as an output parameter rather than totalItems.

I was wondering if you would consider implementing support/overloads for passing that in as an alternative to totalItems which is currently used to calculate totalpages inside the pager code?

Thanks,
Joe

mvcpaging conflicts with footable.js

i have implemented mvcpaging, but this is conflicting with footable.js which was already exists.

i have used pagination css class of bootstrap, which is also used by footable. whenever i apply pagination class on div mvcpagination stops working.

i dont want to remove pagination css class.

Bootstrap DisplayTemplate doesn't support Ajax

Modify the BootstrapPagination.cshtml:

<-- snip --->
var aBuilder = new TagBuilder("a");
if (link.Url == null)
{
aBuilder.MergeAttribute("href", "#");
}
else
{
aBuilder.MergeAttribute("href", link.Url);
if (Model.AjaxOptions != null)
{
foreach (var ajaxOption in Model.AjaxOptions.ToUnobtrusiveHtmlAttributes()) {
aBuilder.MergeAttribute(ajaxOption.Key, (string)ajaxOption.Value);
}
}
}

<-- snap -->

Regards

Problem with AddRouteValue

If i use the following code

@Html.Pager(Model.PageSize, Model.PageIndex, Model.TotalItemCount)
    .Options(o => o.AddRouteValue("query", "a b c"))

the generated url is /search?query=a b c, but it needs to be /search?query=a+b+c

add wrapper for PagerOptions

sometimes, I don't want to display template for custom style.
I just want to wrapper element,
something like:
<span class="cpb">{0}

could you add current page wrapper, and numeric pager wrapper?

Action and RouteValues

Hi,

If I use following code, action parameter is ignored

    @Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount, 
                new AjaxOptions { UpdateTargetId = "gridContainer" })
         .Options(o => o
                    .Action("AjaxMain")
                    .AlwaysAddFirstPageNumber()
                    .DisplayTemplate("Pager")
                    .RouteValues(new { a = "a" })
                    )

but if I change

    @Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount, 
                new AjaxOptions { UpdateTargetId = "gridContainer" })
         .Options(o => o
                    .AlwaysAddFirstPageNumber()
                    .DisplayTemplate("Pager")
                    .RouteValues(new { a = "a" })
                    .Action("AjaxMain")
                    )

everything seems ok.

I believe problem is in RouteValues method. As far as i see, you directly set this.pagerOptions.RouteValues which removes current route values, thus Action value stored in it.

as a workaround, I'm currently setting action parameter after route values.

sincerely

Bootstrap Pagination template is broken with Bootstrap 3

With the CSS changes to Bootstrap 3 the pagination incorrectly renders because the pagination class has moved to the element ul.

See Pagination

Here is what I am currently using which fixes the issues:

// Shared/Bootstrap3Pagination.cshtml
@model PaginationModel
<ul class="pagination">
    @foreach (var link in Model.PaginationLinks)
    {
        @BuildLink(link)
    }
</ul>

@helper BuildLink(PaginationLink link)
{
    var liBuilder = new TagBuilder("li");
    if (link.IsCurrent)
    {
        liBuilder.MergeAttribute("class", "active");
    }
    if (! link.Active)
    {
        liBuilder.MergeAttribute("class", "disabled");
    }

    var aBuilder = new TagBuilder("a");
    if (link.Url == null)
    {
        aBuilder.MergeAttribute("href", "#");
    }
    else
    {
        aBuilder.MergeAttribute("href", link.Url);
    }
    if (link.DisplayText == "ยซ")
    {
        aBuilder.InnerHtml = "&laquo;";
    }
    else if (link.DisplayText == "ยป")
    {
        aBuilder.InnerHtml = "&raquo;";
    }
    else
    {
        aBuilder.SetInnerText(link.DisplayText);        
    }
    liBuilder.InnerHtml = aBuilder.ToString();

    @Html.Raw(liBuilder.ToString())
}

Issue when using PageRouteValueKey option.

There is a bug in Pager.GeneratePageUrl() with respect to the PageRouteValueKey.

This logic:
// Avoid canonical errors when page count is equal to 1.
if (pageNumber == 1 && !this.pagerOptions.AlwaysAddFirstPageNumber)
{
pageLinkValueDictionary = new RouteValueDictionary(this.pagerOptions.RouteValues);
if (routeDataValues.ContainsKey(this.pagerOptions.PageRouteValueKey))
{
routeDataValues.Remove(this.pagerOptions.PageRouteValueKey);
}
}
else
{
pageLinkValueDictionary = new RouteValueDictionary(this.pagerOptions.RouteValues) { { this.pagerOptions.PageRouteValueKey, pageNumber } };
}

Notice your comment is about pagecount=1 however you are not checking pagecount. You are only checking page number. What is happening is that when I use the PageRouteValueKey option, when I am on any page other than the first, the link for the first page triggers the "if" statement and does not append page information at all. ie instead of getting controller/action/id?customPageKey=1 I just get controller/action/id

I was able to fix this by simply creating a class level variable for pageCount and setting that in the BuildPaginationModel method:

public PaginationModel BuildPaginationModel(Func<int, string> generateUrl)
{
var model = new PaginationModel();

        pageCount = (int)Math.Ceiling(totalItemCount / (double)pageSize); //removed "var"
       ...

and then modifying the if statement above to:
if (pageNumber == 1 && pageCount==1 && !this.pagerOptions.AlwaysAddFirstPageNumber)
...
I don't really want to mess with trying to check in this change and possibly messing up something else in your repository but can you please incorporate this change.

AjaxOption Bootstrap3Pagination

I cannot used AjaxOption with Bootstrap3Pagination template. could you provide some example or update the demo?
Thanks.

update:
I'm using BootstrapPagination, but the pager displayed in vertical.
I'm using MVC 5.1.2

ToPagedList() throws Exception for IQueryable

Steps to reproduce

  1. Run a database query that returns an IQueryable
  2. Call ToPagedList() on the IQueryable

Error

The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NotSupportedException: The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.

Stacktrace

[NotSupportedException: The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.]
   System.Data.Objects.ELinq.PassthroughOrderByLifter.Skip(DbExpression k) +94
   System.Data.Objects.ELinq.ExpressionConverter.Skip(DbExpressionBinding input, DbExpression skipCount) +31
   System.Data.Objects.ELinq.SkipTranslator.TranslatePagingOperator(ExpressionConverter parent, DbExpression operand, DbExpression count) +63
   System.Data.Objects.ELinq.PagingTranslator.TranslateUnary(ExpressionConverter parent, DbExpression operand, MethodCallExpression call) +62
   System.Data.Objects.ELinq.UnarySequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) +81
   System.Data.Objects.ELinq.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod) +14
   System.Data.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) +102
   System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54
   System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110
   System.Data.Objects.ELinq.UnarySequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) +58
   System.Data.Objects.ELinq.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod) +14
   System.Data.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) +102
   System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54
   System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110
   System.Data.Objects.ELinq.ExpressionConverter.Convert() +16
   System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption) +110
   System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +149
   System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +44
   System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() +91
   System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +91
   System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) +333
   System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection) +15
   MvcPaging.PagedList`1..ctor(IQueryable`1 source, Int32 index, Int32 pageSize, Nullable`1 totalCount) +1991
   MvcPaging.PagingExtensions.ToPagedList(IQueryable`1 source, Int32 pageIndex, Int32 pageSize, Nullable`1 totalCount) +110
   DocumentManagement.UI.Helpers.Handlers.Filter.AccountListFilterHandler.FilterResults(AccountListModel model) in C:\Users\sbossbaly\Desktop\DocumentManagement\UI\Helpers\Handlers\Filter\AccountListFilterHandler.cs:31
   DocumentManagement.UI.Helpers.FilterActionResult`1.ExecuteResult(ControllerContext context) in C:\Users\sbossbaly\Desktop\DocumentManagement\UI\Helpers\FilterActionResult.cs:44
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260
   System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260
   System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

Workaround

Call ToList() before calling ToPagedList().

Create an empty paged list

Sometimes it is useful to be able to create an empty instance of PagedList. As i did not want to change the library, i worked around this by doing this:

public static class PagedList
{
    /// <summary>
    /// Factory method for an empty <see cref="PagedList{T}"/>
    /// </summary>
    /// <typeparam name="T">Type of data contained in the list</typeparam>
    /// <returns>An empty paged list</returns>
    public static IPagedList<T> Empty<T>()
    {
        return new List<T>().ToPagedList(0, 1);
    }
}

and then using

var empty = PagedList.Empty<SomeType>();

it would be cleaner if i could simply do:

var empty = new PagedList<SomeType>();

No current class if on first page

Hi.

When on first page result, the current link for 1st page has no "current" class applied.

Found this in Pages.cs 81 line

if (i == currentPage || (currentPage <= 0 && i == 0))
{
model.PaginationLinks.Add(new PaginationLink { Active = true, PageIndex = i, IsCurrent = true, DisplayText = i.ToString() });
}

Changed to

if (i == currentPage || (currentPage <= 0 && i == 1))

Works, but don't know if it is the right place to fix it.

Need to be able to specify a prefix for the 'Page' routeValue

I need to be able to specify a prefix for the 'Page' routeValue.

I need to be able to do this as the 'page' routeValue needs to have scope. Currently, I can add a whole load of custom routeValues via options. These custom routeValues all have prefixes of 'Search'

The resulting PaginationLink url is generated as follows:

/search?Search.name=name&Search.email=email&Seach.pagesize=10&page=2

Notice no prefix on 'page'. I need this to be 'search.page' so that it binds correctly to my model.

What I suggest is adding an option to PageOptions.cs (string). When adding the 'page' routeValue to the PaginationLink this option should be taken into account.

Do you accept pull requests?

Avoiding canonical links with paging

Currently the pager would render links such as http://yourwebsite/?page=1. Obviously this can lead to SEO errors with the website rendering identical content for both page 1 and for your index request. The fix is quite simple.

In Pager.cs You just need to alter the GeneratePageLink method from

        var pageLinkValueDictionary = new RouteValueDictionary(linkWithoutPageValuesDictionary) { { "page", pageNumber } };

To

        RouteValueDictionary pageLinkValueDictionary;

        // Avoid canonical errors when page count is equal to 1.
        if (pageNumber == 1)
        {
            pageLinkValueDictionary = new RouteValueDictionary(linkWithoutPageValuesDictionary);
        }
        else
        {
            pageLinkValueDictionary = new RouteValueDictionary(linkWithoutPageValuesDictionary) { { "page", pageNumber } };
        }

Next Link issue on Page 1

I just installed MvcPaging using nuget and I found an issue. When on page 1 the next page number does not have the page query string parameter. As soon as I click on a page number other than 1 it begins to work as expected. The issue does not happen when I reach the last page.

Thank you for the great tool.

MVC 6 and DotNet Core?

Hi Martijn,

Wondering if you have plans to implement this for MVC 6 and the new .NET Core framework? And if so any idea when it might become available?

I'm working on porting an MVC 5 app that uses your pager to MVC 6, so for the moment having to comment out the pagers and wait for a compatible version.

Thanks,

Joe

Last page not showing if same as max number of pages

Hi,
I found an issue when I have the number of pages as same as the default (10) or what I set in the option MaxNrOfPages. The last page does not appear, unless I click on a page closer to the end.
For example, if I have 10 pages on total e set MaxNrOfPages(9), at first it shows only 1 to 9.
Then, if I click on page 7, it shows the pages 1 to 10.

To fix this issue for me, I changed the class Pager, method BuildPaginationModel.
Where it says:
if (end < pageCount - 1) { model.PaginationLinks.Add(new PaginationLink { Active = false, DisplayText = "...", IsSpacer = true }); }
I changed to:
if (end <= pageCount - 1) { model.PaginationLinks.Add(new PaginationLink { Active = false, DisplayText = "...", IsSpacer = true }); }

Then, it shows like this: 1 2 3 4 5 6 7 8 9 ...
For me, this change was enough. Just letting you guys know.

Cheers,

Vanessa

Add Microsoft.AspNet.Mvc as NuGet external package dependency

Currently the System.Web.Mvc.dll (version 5.2.3) is embedded within the MvcPaging project. When used in a web project which uses the latest version (5.2.4), the following warning of DLL versions mismatch appears:

Assuming assembly reference 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' used by 'MvcPaging' matches identity 'System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' of 'System.Web.Mvc'

Microsoft.AspNet.Mvc should be included as a dependency when building the NuGet package (like this package for example: https://www.nuget.org/packages/Twilio.AspNet.Mvc/) to avoid versions mismatch.

Default options

Hi,

I believe there should be an option set default options for pager. Setting DisplayTemplate for each call is extra and unnecessary

Sincerely

Split into 2 assemblies

I really enjoy your library. So much even, that i now have several of my backend layers/api's returning IPagedList<T>. Using the IQueryable<T> extensions, directly within my NHibernate's Linq queries, is also a very smooth experience.

What i really dislike though is the fact that, in order to use the IPagedList<T> throughout my application layers (and thus projects) requires a dependency on System.Web and on MVC. Given i also use that same data access layer in f.ex. WPF apps, means that i get saddled up with needless dependencies.

I would suggest breaking the current project up into 2 separate projects/assemblies/nuget packages. One that holds the abstractions and related extension methods -- which i would use in my non-MVC layers -- , and one that deals with MVC specific things -- which i would use in my UI layer only.

Is this something you would consider for this library, or should i resort to a fork? Dow you want a pull request for this?

AjaxOptions in custom PaginationModel

Hi,
working with MvcPaging I found a potential bug with custom PaginationModel:
There is no way to specify AjaxOptions in the PaginationModel and if I use unobtrusive ajax pagination and custom display template, it does not work.

Thanks.
Raffaele

There is a bug for PagedList

I am sure it's bug for get item start and end.

here is your code:
ItemStart = PageIndex * PageSize + 1; ItemEnd = Math.Min(PageIndex * PageSize + PageSize, TotalItemCount);

If I just have 10 items, pageindex:1, pagesize:10,
Item-Start should be 1 not 11.

Ajax not firing with MVCPaging

Hey Martijnboland,

I see that your MVCPaging package is exactly what I need. Unfortunately I am not getting the desired result like in your demo when using ajax.

I created a stackoverflow question here if you could look it over:
http://stackoverflow.com/questions/13737721/ajax-not-working-with-mvcpaging

basically the ajax part of it is just not working for some reason. When clicking the pager links it just opens a new window with the partial view being rendered instead of updating my element with the next page.

AddRouteValue with an Array of Values

Thanks Martijn for this nice plugin.

I ran into a problem when adding a route value that had an array of values associated with it (such as for a multiple-select ListBox); the GeneratePageUrl function didn't generate the correct URL because the .ToString() method was called on the Array resulting in urls like "/Transfers?Category=System.String%5B%5D&page=3" .

This problem is described here: http://stackoverflow.com/questions/1752721/asp-net-mvc-routedata-and-arrays/
A working solution is here: http://stackoverflow.com/a/5208050/691965

Using the fix from http://stackoverflow.com/a/5208050/691965 , the working GeneratePageUrl function is as-below:

        /// <summary>
        /// Fix RouteValueDictionaries that contain arrays.
        /// Source: http://stackoverflow.com/a/5208050/691965
        /// </summary>
        /// <param name="routes"></param>
        /// <returns></returns>
        private RouteValueDictionary FixListRouteDataValues(RouteValueDictionary routes)
        {
            var newRv = new RouteValueDictionary();
            foreach (var key in routes.Keys)
            {
                object value = routes[key];
                if (value is System.Collections.IEnumerable && !(value is string))
                {
                    int index = 0;
                    foreach (string val in (System.Collections.IEnumerable)value)
                    {
                        newRv.Add(string.Format("{0}[{1}]", key, index), val);
                        index++;
                    }
                }
                else
                {
                    newRv.Add(key, value);
                }
            }

            return newRv;
        }


        private string GeneratePageUrl(int pageNumber)
        {
            var viewContext = this.htmlHelper.ViewContext;
            var routeDataValues = viewContext.RequestContext.RouteData.Values;
            RouteValueDictionary pageLinkValueDictionary;
            // Avoid canonical errors when pageNumber is equal to 1.
            if (pageNumber == 1 && !this.pagerOptions.AlwaysAddFirstPageNumber)
            {
                pageLinkValueDictionary = new RouteValueDictionary(this.pagerOptions.RouteValues);
                if (routeDataValues.ContainsKey(this.pagerOptions.PageRouteValueKey))
                {
                    routeDataValues.Remove(this.pagerOptions.PageRouteValueKey);
                }
            }
            else
            {
                pageLinkValueDictionary = new RouteValueDictionary(this.pagerOptions.RouteValues) { { this.pagerOptions.PageRouteValueKey, pageNumber } };
            }



            // To be sure we get the right route, ensure the controller and action are specified.
            if (!pageLinkValueDictionary.ContainsKey("controller") && routeDataValues.ContainsKey("controller"))
            {
                pageLinkValueDictionary.Add("controller", routeDataValues["controller"]);
            }
            if (!pageLinkValueDictionary.ContainsKey("action") && routeDataValues.ContainsKey("action"))
            {
                pageLinkValueDictionary.Add("action", routeDataValues["action"]);
            }

            // fix the dictionary if there are arrays in it.
            pageLinkValueDictionary = FixListRouteDataValues(pageLinkValueDictionary);

            // 'Render' virtual path.
            var virtualPathForArea = RouteTable.Routes.GetVirtualPathForArea(viewContext.RequestContext, pageLinkValueDictionary);

            return virtualPathForArea == null ? null : virtualPathForArea.VirtualPath;
        }

Cheers,

  • Jason

Add new method AddRouteValueFor

I have a filter field. For example:

@Html.Pager(pageSize, pageNumber, totalItemCount).Options(o => o
.AddRouteValue("Filter.Name", Model.Filter.Name)
.AddRouteValue("Filter.City", Model.Filter.City)
.AddRouteValue("Filter.Postcode", Model.Filter.Postcode)
)

I think a good idea would be to add a new method AddRouteValueFor. For example:
@Html.Pager(pageSize, pageNumber, totalItemCount).Options(o => o
.AddRouteValueFor(m => m.Filter.Name)
.AddRouteValueFor(m => m.Filter.City)
.AddRouteValueFor(m => m.Model.Filter.Postcode)
)

BuildPaginationModel() Performance

First, great extension! I really like this.

I'm seeing some issues with the BuildPaginationModel() method. With a very small paged list (so or less items) it seems to perform OK. However, with a larger list (1500 items) the method is really very slow. AJAX calls take about 8-9 seconds to complete when paging and this is on a good machine. I'd be happy to provide you with any further information you may need to resolve this. Thanks!

mvcpaging dateformat change in url

i have used mvcpaging with date time search filter. date field accepts date in dd/MM/yyyy format.

after searching for a specific date when i click on pager to go on 2nd page it added this date in url but date format is changes to mm/dd/yyyy format.

i dont want to change the format of date.

please suggest how can i do this.

thanks in advance.

MaxNrOfPages behaves oddly at small page counts

I have a PagedList with 8 pages.

If I set .Options(o => o.MaxNrOfPages(3)), and change to page 5, I get this:

[First] 1 2 ... 4 5 6 ... 8 [Last]

On page 4 it looks like:
[First] 1 ... 3 4 5 ... 7 8 [Last]

In either case, I expect to get 3 pages, not 6, and it would be nice if the Pager was smart enough in any event to realize that the "..." is skipping exactly one page, in which case it's better to render the page link. I don't need links to page 1 / 2 / 7 /8, that's why I have First and Last links.

ActiveLink

In file src/MVCPaging/Pager.cs
in line 95 PaginationLink with text "..." is active.
I think it has to be inactive
model.PaginationLinks.Add(new PaginationLink { Active = false, DisplayText = "..." });

AddRouteValue and RouteValues conflict

I am using MvcPaging 2.1.0 downloaded by nuget

@Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount,
    new AjaxOptions
    {
        UpdateTargetId = "PreOrderListContainer",
        OnSuccess = "indexAjaxCallback"
    }).Options(
        o => o.Action("IndexAjax")
              .AddRouteValue("sortOrder", ViewBag.sortOrder)
              .RouteValues(ViewBag.RouteValueDict)
              .DisplayTemplate("Bootstrap3Pagination")
              .MaxNrOfPages(10)
              .AlwaysAddFirstPageNumber()
)

The above pager will ignore the route value provided by AddRouteValue("sortOrder", ViewBag.sortOrder). i.e. the sortOrder will not be exists in the pager link generated.

I change Pager.Options lambda as below, i.e. use RouteValues before AddRouteValues.

o => o.Action("IndexAjax")
      .RouteValues(ViewBag.RouteValueDict)
      .AddRouteValue("sortOrder", ViewBag.sortOrder)
      .DisplayTemplate("Bootstrap3Pagination")
      .MaxNrOfPages(10)
      .AlwaysAddFirstPageNumber()

Both of the route values provided by RouteValues and AddRouteValue will be exists in the pager link generated.

Ajax Paging and Bootstrap 3 Pagination

I used Ajax Paging and DisplayTemplate("Bootstrap3Pagination").

My steps:

  1. Click "2" button
  2. Click "1" button
  3. Click "<<" button - send a request (without the route values). This action should not do anything.

See picture below:

error

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.