Category Archives: Paging

Paging

[RESOLVED]Best industry used approach to implement paging in MVC

Hi all,

I need to implement paging on MVC4 project. I have come across multiple solutions for the same on the web but couldn’t decide what would be the best one to choose or say which is widely used as a industry standard.

I have around 50, 000 records in the database that satisfy the criteria and page size is 50. I want to hit the DB and load only specific 50 records each time whenever user selects a page.

Suggestions pls???

MVC is a presentation framework, it doesn’t concern itself with data paging.  If you’re using Entity Framework then you can look at this for examples of paging

http://msdn.microsoft.com/en-us/magazine/gg650669.aspx

I don’t think it is all that efficient if you have a lot of data though, you’d need to examine the sql that gets created.  Or you can do your own paging at an SP level

http://www.codeproject.com/Articles/590341/Stored-Procedure-with-Sorting-Paging-and-Filtering

http://stackoverflow.com/questions/15676685/paging-of-records-using-sql-server-stored-procedure

Thanks for the reply AidyF.

Would you recommend using PageList.MVC NuGet Package over using SP?

You have to have a dig into the queries things execute and how they work to make sure it is compatible with the amount of data you have.  Some jQuery-based pagers simply get all data and page through it in code, which can be fast but isn’t good if you have
hundreds of thousands of items.  Some will execute ajax requests back to retrieve each page, and as long as your data retrieval is efficient this would be the best ajax-related approach.  But again how you implement server-side paging also has an impact as
things like .Skip().Take() could result in a lot of waste SQL resources and slow queries.  If you have a lot of data you need a solution that doesn’t get every result and page in-memory, and you need to make sure that the code you use to get the data from
your database is also efficient.

[RESOLVED]How do display the PartialView result in 1 <div>?

Hi,

I’m working on a MVC3 web appl, with c#, Razor view. On 1 long view page, for a certain section, there is a
@Html.Action(….) where a PartialView will be displayed.

Now, a new requirement is raised to add paging to this PartialView; so that the height of this section is fixed, and won’t grow indefinitely.

What I did is: in the controller action, I write the data into a ViewModel, and use PagedList in this PartialView to add paging.

The 1st page works great; but when I click the "next" link at the bottom of this section, to go to the 2nd page, it goes to a TOTALLY NEW page, in a new browser windnow – I need the 2nd, 3rd and all the rest of the pages to stay in the SAME section; so when
I click "Next", the content for the next page will show up in the same <div>, while the rest of the page remains the same.

Is there a simple way to do this?

Thanks,

Claudia

specify the div id to the webgrid

new WebGrid(..., ajaxUpdateContainerId: "divid"............

Thanks for the suggestion.

Actually my Viewmodel is a bit complicated…it has some info to be presented in a table; the rest are either in a list, o just plain text (not in a table or list).

The WebGrid idea seems to put everydata in the ViewModel into a table….correct?

If so, it does not work for my situation. I’ve looked into jQuery DataTables as well – it does not work for the same reason: the data from my ViewModel here requires more than a table.

I just need to automatically update this 1 <div>; and keep displaying all data here in this 1 div, with paging — is there a similar idea to use for a <div>, not WebGrid div, but with the ‘ajaxUpdateCOntainerID = "myDiv"? I’ve looked around, but did not
find any attribute for <div>….

Here is my current code:

<div id="result">

    @Html.Action("ResultPartial", "MyController", new { id = id } );

</div>

And in "ResultPartial" view page, I use "PagedList" to add  pagination. In the controller action for "ResultPartial", I aggregate the data and write them into a ViewModel.

I’m trying to use something like this (see below), but have not found a way to make it work for @Html.Action:

new AjaxOptions{ HttpMethod = "GET", 
UpdateTargetId =
"result",
InsertionMode =
InsertionMode.Replace }

Thanks,

Claudia

Update – I searched around and tried more. I think I found the core issue: it is in the bottom "Pagination links", the code comes with the PagedList – when I click "Next" or "Prev", which is an @Html.ActionLink, I want it to stay on the same page, however,
it went off to a new page.

This is the code for it right now:

@Html.ActionLink("Next", "ShowResultPartial", new { page = Model.PageNumber + 1, sortOrder = Viewbag.CurrentSort, currentFilter = ViewBag.CurrentFilter,
UpdateTargetId = "result" }, new {@class = "paging_link"})

Note: I added the bold part UpdatetargetId = "result" – but this does not work.

Note: I tried to use @Ajax.ActionLink("Show Result",
"ShowResultPartial",
new
AjaxOptions{UpdateTargetId="statusresult" }) – which has the "UpdateTargetId" attribute; however, with Ajax.ActionLink, I can  not write all other attribute such as  "page", "sortOrder"…

So – I really need a combination here – I need to use either 1) @Html.ActionLink but add "UpdateTargetId" and make it work; or
2) use @Ajax.ActionLink but be able to add all other attributes for pagination.

Anyone has a suggestion?

I have spent quite some time on this already, and have a deadline tomorrow … any advice will be much appreciated!

Thanks a lot,

Claudia

Hi Claudia,

You could specify the additional data in the Ajax.ActionLink, please use this override method:

# AjaxExtensions.ActionLink Method (AjaxHelper, String, String, Object, AjaxOptions)

http://msdn.microsoft.com/en-us/library/dd470364(v=vs.118).aspx

Best Regards

Starain

Hi Starain,

Thanks for the suggestion. Can you provide some sample code using @AjaxExtensions.ActionLink(…)? I read the MSDN article but still not sure how to use it; plus, all the examples I found  are using @Ajax.ActionLink(….)…

Thanks,

Claudia

Hi Claudia,

Please refer to this code below:

 @Ajax.ActionLink("linkText", "ActionName", new { page = 2, sortOrder = "desc" }, new AjaxOptions { UpdateTargetId = "statusresult" })

Best Regards

Starain

Hi Starain,

I tried this code….however, it still does not work yet. HEre is my situation:

I have a main page, "ShowResult.cshtml". On this page, there are 3 sections:

<div id="top">

 ….

</div>

<div id="result">

  @Html.Action("ShowResultPartial", "MyController", new { id = id }) // this will call an action which generates a partialview, with paging at the bottom

</div>

<div id="bottom">

</div>

Now,  in the partialview "ShowResultPartial.cshtml", I used the @Ajax.ActionLink code you suggested. it is for the pagination; I use PagedList for this page:

@model PagedList.IPagedList<MyModel.ViewModels.ShowResult>

….

@Ajax.ActionLink("Next", "ShowResultPartial", new { page = Model.PageNumber + 1, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter },  new AjaxOptions { UpdateTagetId = "result" })

Now, the main page "ShowResult.cshmtl" displays everything right, with the 1st page of ShowResultPartial.cshtml; BUT, when I click on "Next", the 2nd page of "ShowResultPartial.cshtml" now REPLACED the main "ShowResult.cshtml" page – and this is NOT what
I want to achieve.

What I want to achieve is: the main page, ShowResult.cshtml, REMAINS the same. And the pagination is only for the <div id="result"> section, not for the whole page (that is why I used the PartialView for that part of the content); so only in this div, in
the middle section of the ShowResult.cshtml page, there will be the content generated from ShowResultPartial.cshtml, with pagination at the bottom of this section; and when I click on "Next", ONLY this section or <div id="result"> should be updated with the
content for the next page; the other parts of the ShowResult.cshtml page should not move or change; nor should the url of this page be changed either.

I hope that I’m clear on the description of my issue….

Please let me know if you have any creative ideas to make this happen?

Thanks,

Claudia

I think Partial view doesnt use _Layout page, So what you can do is you can use use ajax for calling the controller action for paging . I don’t want to go in detail about how to use ajax for paging, i hope you are well aware of this. 

Update – I have solved this issue.

Thanks everyone for helping,

Claudia

[RESOLVED]Pros and cons of using Web grids inside asp.net vmc web applications

In my previous asp.net mvc web projects, I use to manually do column sorting, filtering , search , etc.

But now I read about available web grids plugins, such as jqGrid, jtable, etc. and it can save me a lot of time to deliver sort, filter, paging features. But I have a couple of questions about using these web grids inside asp.net mvc views, as it seems that
I will lose important asp.net mvc features when using these web grids.

  • For example when building a jqgrid, i will be writing something such as the following inside my razor view:-
    <script type="text/javascript">
        jQuery("#jQGridDemo").jqGrid({
            url: '',
            datatype: "json",
            colNames: ['Id','First Name', 'Last Name', 'Last 4 SSN', 'Department', 
                    'Age', 'Salary',  "Address",'Marital Status'],
            colModel: [
            { name: '_id', index: '_id', width: 20, stype: 'text' },
            { name: 'FirstName', index: 'FirstName', width: 150 },
            { name: 'LastName', index: 'LastName', width: 150 },
               { name: 'LastSSN', index: 'LastSSN', width: 100 },
            { name: 'Department', index: 'Department', width: 80, align: "right" },
            { name: 'Age', index: 'Salary', width: 80, align: "right" },
            { name: 'Salary', index: 'Salary', width: 80, align: "right" },
            { name: 'Address', index: 'Address', width: 150, sortable: false },
            { name: 'MaritalStatus', index: 'MaritalStatus', width: 100, sortable: false }
          ],
            rowNum: 10,
            sortname: 'id',
            viewrecords: true,
            sortorder: "desc",
            caption: "List Employee Details"
        });
    </script>

So in this case i am manually writing the column names such as “FirstName”, “LastName” , etc , instead of relying on html templeted helpers such as Html.DisplayFor(modelitem=>modelitem.FirstName) . so I will lose the benefits of having strongly typed views.
also the generated field names and their values will not be based on what has been defined inside the data annotation such as [DisplayName("First Name")] . So does this mean if I use jqGrid or other web grids, i will lose the effect of any data annotations
such as DisplayName, since I will be manually writing the field names on each view ?.

  • Also all the examples which i read about jqGrid pass json to the Grid. So does jqGrid accept Model objects passed from action methods to view or it only work with json ?

  • Now when I create a new item inside the jqGrid, I will do this inside a jquery dialog and not inside normal view.so this means that the Data annotation used for validation which I define inside my model class such as [Required], [Length] will not have any
    effect inside the jquery dialogs , is this correct ?. Because from my current experience with jquery dialogs they will ignore DataAnnotation defined inside the Model class, also if I add error inside ModelState provided by asp.net mvc , then I will not be
    able to show the modelstate errors inside the dialog if an exception occurred in the Post Create action method , ?

Can anyone advice on these points and if they are valid when using web grids with asp.net mvc ?

There is a MVC webgrid that enables you to use the MVC style of helpers

WebGrid in ASP.NET
MVC4

pprasannak

There is a MVC webgrid that enables you to use the MVC style of helpers

WebGrid in ASP.NET
MVC4

thanks for the reply. but can i know if you have use it before and how did you find it compared to other grids such as jqGrid, SlickGrid.

Second question. is there other MVC-based grids which i can use?

Thanks a lot for the help…

johnjohn123123

but can i know if you have use it before and how did you find it compared to other grids such as jqGrid,

SlickGrid

I used MVC WebGrid and JqGrid. It all depends on what functionality you are looking. If you need a simple grid with basic functionality like sorting, paging then go for webgrid. Is there a specific functionality you are looking in JqGrid

johnjohn123123

is there other MVC-based grids which i can use?

I really like DataTables, it has so many functionalities. There is also an MVC extension for this. Please take a look at their website

DataTables | Table plug-in for jQuery

Strongly typed datatable example

first thanks a lot for your help.

pprasannak

It all depends on what functionality you are looking. If you need a simple grid with basic functionality like sorting, paging then go for webgrid. Is there a specific functionality you are looking in JqGrid

I mainly want these main features; paging, column based sort, column based filter, search , export to csv files and ability for the grid to work with model objects in-addition to json. an optional feature is column based edit .

pprasannak

I really like DataTables, it has so many functionalities. There is also an MVC extension for this. Please take a look at their website

for sure i will read these links, but if i am not wrong , jqGrid does not have an mvc extension , is this correct?

I checked the strongly typed datatable on this link
http://mvcjquerydatatables.apphb.com/
, and the controller will be as follow:-

public class SomeController : Controller 
{
    ...
    public DataTablesResult<UserView> GetUsers(DataTablesParam dataTableParam)
    {
        IQueryable<User> users = ... //take a queryable from your database...
        var userViews = users.Select(u => new UserView(u)); //...transform it into a view object ...
        return DataTablesResult.Create(userViews, dataTableParam)  //...and return a DataTablesResult
    }
}

so if i am not wrong i will be sending all the objects from the database to the client and then do paging and filtering on the client side ? as in the above code they are not passing any paging and filtering info ? can you advice if dataTables supports server
side paging and filtering ?

Thanks

johnjohn123123

can you advice if dataTables supports server side paging and filtering ?

Server-side processing in DataTables

How to Create Server-Side Paging for DataTables.Net with ASP.Net

Glad to see the last comment use the word "Server Side" turns out there are a number of client side grids too…. in particular DataTables.NET which is as simple and functional as they get.  It allows you to either bind directly to it via Javascript and
JSON objects, or you can use MVC model binding to create the well-formed table and write the proper javascript so it’s recognized by DataTables.js

How to show blog posts one below the other?

I am writing a blog app. on MVC 4. I am designing the home page where blog posts appear one below the other.

What to use to show this type of display? There should be pagination. I want only five posts per page.

rpk2006

What to use to show this type of display? There should be pagination. I want only five posts per page.

First, you must define how you make the pagination( url, hidden fields, javascript, ajax …)
Then you can read MVC tutorials for pagination

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

I would also suggest reading a bit on HTML and Bootstrap – that might help you much.

A good site to start with is

http://www.w3schools.com/html/html5_intro.asp

http://www.w3schools.com/bootstrap/default.asp

@ignatandrei:

Pagination is OK. The first part is how to show posts one below the other.

Go through some basic tutorials on MVC and they’ll cover this kind of thing, to show things in a list just output them in a for loop.

@model IEnumerable<SomeModelThatHoldsYourBlogData>

@foreach(var blog in Model)
{
    <h1>@Html.ActionLink(blog.Title, "View", "Blog", new {id=blog.ID})</h1>
    <h2>@blog.DateUpdated.ToString("dd MMM yy") by @blog.Author</h2>
    <p>
        @blog.SummaryText
    </p>
}

[RESOLVED]WebGrid with Pagination for Delete Operation

Hi

I am using webgrid to display the list of records. Now I want to implement the delete functionality with paging.

For example:

if we have 21 records and gird show 10 records per page. So here, grid will have
3 pages. On the last page, there is only 1 record.

Now, when we perform delete operation, the grid should show the
previous page. i.e. 2nd page

Currently,  gird shows no records for the 3rd page. Since last record is deleted.

Kindly help in this case. 

Thanks

you would need to rebind the webgrid after deleting the record

refresh page after deleting record that will rebind web grid.

Hi,

According to your description, I think you delete the record through AJAX and remove the item directly.

For this issue, you need to handle that scenario manually, check current page whether there is the data, if not, get retrieve previous page’s data and display.

Best Regards

Starain

[RESOLVED]ASP,NET MVC 4 Ajax Paging with Filter

Hello,

I have an ASP.NET MVC 4 application to implement log viewing page with ajax paging using PagedList and PagedList.Mvc(got from NuGet). I also implement two filters with displaying the table. My question is how could I pass the filter with ajax call.

My code:

Controller:

public ActionResult Logs(string currentFiler, int? page)
{

     const int pageSize = 10; //for testing purpose, to be adjustetd
     int pageIndex = (page ?? 1) – 1;
     int pageNumber = (page ?? 1);

     IEnumerable<LoggingDashBoardViewModel> logs = _logReportingReposioty.GetAllLogs().OrderByDescending(d => d.LogDateTime);//.Take(10); //.Skip(pageSize * (page – 1));

     var Logs = logs.ToPagedList(pageNumber, pageSize);

     if (Request.IsAjaxRequest())
     return PartialView("_Logs", Logs);

     return View(Logs);
}

View(Logs.cshtml):

@model PagedList.IPagedList<ProMaster.Infrastructure.Logging.ViewModels.LoggingDashBoardViewModel>

<div class="content_info">
<div class="log_head" style="margin-top: -.5em; width: 97%; margin-left: -0.1em;">
<span>
Log Level:
<select id="level" style="background-color: rgb(238, 240, 241); font-size: .95em;">
<option value="1">ALL</option>
<option value="2">INFO</option>
<option value="3">WARN</option>
<option value="4">ERROR</option>
</select>
</span>
<span>
Log Period:
<select id="period" style="background-color: rgb(238, 240, 241); font-size: .95em;">
<option value="1">All</option>
<option value="2">Last 7 Days</option>
<option value="3">Last 14 Days</option>
<option value="4">Last 30 Days</option>
<option value="5">Last 180 Days</option>
</select>
</span>

</div>

<div id="loglist">
@Html.Partial("_Logs")

</div>

<br />

</div>

and ParialView(_Logs.cshtml)

<table>

….

</table>

<span id="pager" style="float:right;">

     @Html.PagedListPager(Model, page => Url.Action("Logs", new { page, currenFilter = ViewBag.CurrentFiler }), new PagedListRenderOptions {

           LinkToFirstPageFormat = "<<",
           LinkToPreviousPageFormat = "<",
           LinkToNextPageFormat = ">",
           LinkToLastPageFormat = ">>",

})

</span>

<script type="text/javascript">

$(‘#pager’).on(‘click’, ‘a’, function () {
/

$.ajax({
url: this.href,
type: ‘GET’,
cache: false,
success: function (result) {
$(‘#loglist’).html(result);
}
});
return false;
});
</script>

The issue I have is the first ajax call with filter works as expected, but by clicking on 2nd page, the filter is lost, I guess I need to get the filter inside the ajax call, but how, please help and point me to a solution.

Thanks so much in advance.

Hi,

According to your discription, it seems that maybe your search string for filter is lost by clicking on 2nd page. If that, you can try passing the parameter via using the data option of the $.ajax function.

For more information, please refer to the similar discussion:

http://stackoverflow.com/questions/8486132/jquery-ajax-passing-value-from-mvc-view-to-controller

[RESOLVED]Order groups in JQGrid

I have the below data

Category Order Item
A 3 ITM1
B 1 ITM2
C 2 ITM3

I want to display this data in JQGrid as below  

  Item
B  
  ITM2
C  
  ITM3
A  
  ITM1

Hi Kalyan,

You could use the JQGridSortEventArgs passed to the Sorting event to detect the column being sorted and the sort direction. Here is an example of overridiing the default sorting logic:

<trirand:JQGrid runat="server" ID="JQGrid1" Width="600px" OnSorting="CustomSortingGrid_Sorting">

protected void CustomSortingGrid_Sorting(object sender, Trirand.Web.UI.WebControls.JQGridSortEventArgs e)
{
    // Cancel the default sorting, which essentially sorts the clicked column
    e.Cancel = true; 

    // Get data from the datasource
    DataTable dt = GetData(); 
    // Set sorting to always sort using the ID column
    // You can change that using the event arguments e.SortExpression (column name) and 
    // e.SortDirection (asc / desc)
    dt.DefaultView.Sort = "CustomerID " + e.SortDirection.ToString().ToUpper();            

    // Rebind the grid using the sorted DataTable
    JQGrid1.DataSource = dt;
    JQGrid1.DataBind();
}

More details, please refer

http://www.trirand.net/documentation/aspnet/_2s90o9ffz.htm

Besides, here are some similar threads, perhaps they can helps you.

JQGrid – SortCol Not Working.

JqGrid Searching, Sorting, Paging,
Freejing, Coulmn Show Hiding with…

Best Regards,
Dillion

[RESOLVED]Modify pagination in Mads Kristensen's asp.net miniBlog

I setup the miniBlog on azure and I want to modify the pagination to show the prev/next and five page numbers. The miniBlog is a databaseless blog and I’m not sure how to go about it. Does anyone have any suggestions or sample code?

Source is on: https://github.com/madskristensen/MiniBlog

The paging is controlled in the layout file which is in the Themes directory. By default the OneColumn theme is being used. You can change the logic there. 

[RESOLVED]How to get automatic next page in cshtml ?

Hi all,

Can I edit to get automatic next page in the following cshtml code : ( Eg: Previouse 2 3 4 5 Next )

@{
var db = Database.Open("SmallBakery"); 
var selectQueryString = "SELECT * FROM Product ORDER BY Name"; 
}

<html> 
<body> 
<h1>Small Bakery Products</h1> 
<table> 
<tr>
<th>Id</th> 
<th>Product</th> 
<th>Description</th> 
<th>Price</th> 
</tr>
@foreach(var row in db.Query(selectQueryString))
{

<tr> 
<td>@row.Id</td> 
<td>@row.Name</td> 
<td>@row.Description</td> 
<td style="text-align:right">@row.Price</td> 
</tr> 
}
</table> 
</body> 
</html>

Help me please ? Thanks..

You can add your own paging. I cover how to do that in this article: http://www.mikesdotnetting.com/article/150/web-pages-efficient-paging-without-the-webgrid

Hello,

You can use WebGrid Helper:

@{
var db = Database.Open("SmallBakery"); 
var selectQueryString = "SELECT * FROM Product ORDER BY Name"; 
var grid = new WebGrid(source: selectQueryString, rowsPerPage: 10);
}

<html> 
<body>
   @grid.GetHtml()
</body> 
</html>

rowsPerPage specifies how many items will be displayed on each page.

You can find more information on the following page:

http://www.asp.net/web-pages/overview/getting-started/introducing-aspnet-web-pages-2/displaying-data

Good luck..

Hello,

what is your result?

Did you try the solutions?

Hi Mike, how would you go about limiting the number of page links shown. I can see you having a large number of them if there is a lot of data?

Something like this could make the work:

    <a href="/Paging/1">First</a>
    @{
        var startingPage = 1;
        if (totalPages >= 5) 
        {
            if((page - 2) > 0 && (page + 2) <= totalPages)
            {
                startingPage = page - 2;
            } else if ((page + 2) > totalPages)
            {
                startingPage = totalPages - 4;
            }
        }
        for (var i = startingPage; i <= startingPage + 4 && i <= totalPages; i++){
            <a href="/Paging/@i">@i</a>
        }
    }
    <a href="/Paging/@totalPages">Last</a>

Maybe the code could be optimized …

Hi ayanmesut,

Thanks for your help. This way I already learns from you but I want such as
Mekis
article example… Thank you.