Add Simple Ajax Paging to Grids in ASP.NET MVC

Introduction

In standard ASP.NET it is very easy to implement a full featured data grid with paging. With the help of an UpdatePanel you can improve the user experience of paging data in grids by taking advantage of Ajax (Asynchromous JavaScript And XML). With the UpdatePanel you are isolating a small portion of the page to refresh, in this case only the Grid. In ASP.NET MVC (Model-View-Controller) the simpliest method of rendering only a portion of a page is through a partial view. Partial views can be extremly handy for rendering an area of a page similar to an Update Panel; however, out of the box they do not provide the JavaScript necessary to carry out the update themselves. Thus we need to take advantage of the MVC Ajax JavaScript class. In addtion to the ability to update the page we also need to render out the control the user will use to change pages displayed within the grid.

Before we dig into the partial view to house the grid we need to take a look at the paging mechanism we will be using. Ideally we would want to create a tool which is reusable across multiple grids within a site. One method for doing this is by creating a specific extension helper method to create a generic Pager. Since we are going to utilze Ajax for this we will want to create an Ajax Helper Method. To build the pager code itself we are going to need a couple inputs: current page, page size and total records. In addition, we will need to know the action to call and the target DIV tag which is used by the Ajax method to determine where to put the content returned from the action. From there we can create a simple extension method to generate a pager using the code below.

  public static MvcHtmlString Pager(this AjaxHelper helper, int CurrentPage, int TotalRecords, string TargetDiv, int PageSize = 10, string ActionName="Index")
  {
     if (TotalRecords > 0)
     {
        StringBuilder sb = new StringBuilder();
        int TotalPages = (int)Math.Ceiling(TotalRecords / (double)PageSize);
  
        //Build the Ajax Options
        AjaxOptions ao = new AjaxOptions();
        ao.UpdateTargetId = TargetDiv;
  
        if (CurrentPage > 0)
        {
           //Add the Back Links
           sb.Append(System.Web.Mvc.Ajax.AjaxExtensions.ActionLink(helper, "<<", ActionName, new { Page = 0 }, ao));
           sb.Append("  ");
           sb.Append(System.Web.Mvc.Ajax.AjaxExtensions.ActionLink(helper, "<", ActionName, new { Page = CurrentPage - 1 }, ao));
           sb.Append("  ");
        }
  
        //Add the Page Number
        sb.Append("Page " + (CurrentPage + 1).ToString() + " of " + (TotalPages).ToString());
  
        if (CurrentPage < (TotalPages - 1))
        {
           //Add the Next Links
           sb.Append("  ");
           sb.Append(System.Web.Mvc.Ajax.AjaxExtensions.ActionLink(helper, ">", ActionName, new { Page = CurrentPage + 1 }, ao));
           sb.Append("  ");
           sb.Append(System.Web.Mvc.Ajax.AjaxExtensions.ActionLink(helper, ">>", ActionName, new { Page = TotalPages }, ao));
        }
  
        return MvcHtmlString.Create(sb.ToString());
     }
     else
     {
        //Don't return anything for the pager if we do not have any records
        return MvcHtmlString.Create("");
     }
  } 

The above code, while a bit lengthly, performs a very simple task to generate a simple pager that looks like the following example: <<  <  Page # of ##  >  >>.  The method first determines if we actually have any records in the grid, if not do not generate it. Then we calculate the total number of pages for the given page size and the number of records. From there it populates a string builder with the necessary Ajax ActionLinks going to the desired Action with the specified Page number and returns the MvcHtmlString containing the necessary markup.

At this point, it is important to note that the Ajax ActionLinks drive what Action to call and where to put the resulting content based upon the parameters given. The AjaxOptions object specifies the Update Target Id as well as other options we are not using such as JavaScript methods to call when an update occurs. To start using the pager we need an action which accepts page as a parameter and returns a partial view. Next we can take a look at the controller action which can be called by the pager extension method.

public ActionResult Index(int Page = 0)
{
   int PageSize = 10;

   Models.Contacts c = new Models.Contacts();
   List cList = c.GetAll();

   ViewData["TotalRecords"] = cList.Count();
   ViewData["Contacts"] = cList.Skip(Page * PageSize).Take(PageSize).ToList();
   ViewData["CurrentPage"] = Page;

   return PartialView("Index");
}

As you can see this action accepts the page parameter with a default value of 0. The default value can come in handy later, allowing you to render the partial view without the need for a page number. From the Contacts data source the method grabs the total number of records, the current page number and returns a list of records as contacts. The list of records has been filtered to provide a single page of data using the Skip and Take LINQ (Language Integrated Query) methods. In this example we are using a simple generic list; however, the paging should be extended down to the model to return only those records needed and limit the amount of data read from the database.

Next we can jump into the Partial View which serves to connect the data from the Index Action as well as utilizing the pager extension method above. Shown below is the index partial view used in the index action.

  <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
  <table>
   
     <tr>
        <th>FirstName</th>
        <th> LastName</th>
     </tr>
  
     <% foreach (var item in Ajax.ViewData["Contacts"] as List<MVCGridPagingExample.Models.ContactItem> ) { %>
     <tr>
        <td><%: item.FirstName %></td>
        <td><%: item.LastName %></td>
     </tr>
     <% } %>
  
  </table>
  <%: Ajax.Pager((int)Ajax.ViewData["CurrentPage"], (int)Ajax.ViewData["TotalRecords"], "ContactsDiv")%> 

This partial view, as you would guess generates a table/grid with the list of contacts; however, there is one disction that I should point out. Within the foreach loop we are using Ajax.ViewData instead of Html.ViewData. This allows us to use the ViewData with Ajax calls in addition to standard GET requests. The last line of the Partial View is where we insert the call to the pager extension method we created above. In the call we are passing in the items needed which we are receiving in the ViewData from the action method. You may have already noticed that the ContactsDiv specified in the last parameter doesn't exist anywhere in the partial view. The ContactsDiv wraps around where you want this partial view to be displayed as shown below.

  <div id="ContactsDiv">
     <% Html.RenderAction("Index", "Contacts"); %>
  </div> 

The Html.RenderAction is primarily used to start the process and initially call the index action created above. This will produce the partial view containing the grid as well as the pager. Then as the user clicks to change the page using the pager the Ajax ActionLinks will make the call to the index action and return the partial view containing the desired page. Finally, the AJAX ActionLink will replace the contents of the ContactsDiv with the returned data.

Conclusion

This simple technique illustrated above illustrates just how easy it is to create complex items within the MVC framework. You could very easily expand upon this to delivers clickable page numbers similar to many sites. While the scheme is a bit more complex within the pager helper method it is not a drastic change. You could also use this technique to produce the alphabet for searching through a contact list, as an example. Furthermore, this article really demonstrates the difference in thinking needed for creating the necessary components within a site with the MVC Framework versus the standard ASP.NET Framework.



About the Author

Chris Bennett

Chris Bennett is a Manager with Crowe Horwath LLP in the Indianapolis office. He can be reached at chris.bennett@crowehorwath.com.

Related Articles

Comments

  • gucci バッグ新作=http://www.oncomingimages.com/list/guccikudasaii.html

    Posted by fubyGriff on 07/16/2013 08:07am

    [url=http://www.oncomingimages.com/list/marccity.php]マークバイマークジェイコブス トート[/url] [url=http://www.oncomingimages.com/list/marcbags.php]マークバイマークジェイコブス 財布[/url] [url=http://www.oncomingimages.com/list/jimmychooseiru.php]ジミーチュウ アウトレット[/url] GUCCI バッグ斜め掛け=http://www.oncomingimages.com/list/guccikudasaii.html ジミーチュウ アウトレット=http://www.oncomingimages.com/list/jimmychoolovely.html [url=http://www.oncomingimages.com/list/guccicategory.html]グッチ 財布 アウトレット[/url] [url=http://www.oncomingimages.com/list/jimmychoolist.php]ジミーチュウ アウトレット[/url] 要は、月1す。私的れていま効果を用対効果・キーワりかなりの知識上げるだでが高いキー出てくる業者す。(その業種のロ [url=http://www.oncomingimages.com/list/coachcollection.php]コーチ[/url] ジミーチュウ アウトレット=http://www.oncomingimages.com/list/jimmychoolist.php [url=http://www.oncomingimages.com/list/jimmychoolovely.html]ジミーチュウ バッグジミーチュウ 店舗[/url] ジミーチュウ 靴=http://www.oncomingimages.com/list/cheapjimmychoo.html [url=http://www.oncomingimages.com/list/jimmychoosale.html]ジミーチュウ サンダル[/url] ジミーチュウ メンズ=http://www.oncomingimages.com/list/jimmychoosale.html [url=http://www.oncomingimages.com/list/guccikudasaii.html]gucci バッグ新作[/url] グッチ トートバッグ=http://www.oncomingimages.com/list/guccicategory.html マークバイマークジェイコブス トート=http://www.oncomingimages.com/list/marcbags.php することがザビリだけで全ペジを修正するこイアウト的に見るイルが検ってしまってしまうメニューが場合は、埋め込めるキーワードがいと考えます。ただしフレーム検索の情きです。当然な。 マークバイマークジェイコブス バッグ=http://www.oncomingimages.com/list/marccity.php ジミーチュウ セール=http://www.oncomingimages.com/list/jimmychooseiru.php [url=http://www.oncomingimages.com/list/cheapjimmychoo.html]ジミーチュウ スニーカー[/url] コーチ バッグ=http://www.oncomingimages.com/list/coachcollection.php

    Reply
  • A spread Phone said table

    Posted by dqiggaAV on 07/12/2013 05:04am

    louboutin shoes , Bankruptcy in than you will

    Reply
  • Michael Kors Hamilton

    Posted by gogofpo on 07/06/2013 04:07pm

    Michael Kors Handbags Was Designed To Be Simple And Bold Eating a heavy meal on board will distribute much of the oxygen to your stomach for digestion and, With less oxygen in a pressurised log home, This could make you feel groggy and even faint. Digestion is sluggish on flights so you should eat in edinburgh airport before takeoff: You won't be hungry until the end and your digestion will be better. Try to get some sleep during the flight if you arrive somewhere every morning, feel feel fresher, (127 cm) Long and may think about to 25 lb (11 kg). on the go both day and night, The coati is a forest occupant and an agile tree climber. It takes lizards, birds, And fruit and uses its long mobile snout to grub for pestilence and roots. cut-throat nature has made me who I am today. Amy ended her career as the sixthleading scorer in Tech record with 1,444 stages. The 2000 Atlantic 10 defensive player of the year also ranks second in steals (235) And third in permits (399), 3d nail stickers are non confused something of that nature. Percy work was suitable "Prometheus Unbound" A run. we were holding both begun in about 1818 (Also during the time, Mary was transcribing Percy take up) The parallels are concerning, But romantic relationship. feel Frankenstein was Mary work, She was just able to rely on a okay adviser. What to Do If Your Workers' compensation claim Has Been Denied There might be lesser benefits for the applicant. I do not know of any absolute, Foolproof way of finding the optimum doctors in a given specialty. Some health plans ask you to see only a physician from a special list provided by the insurer, Meaning your family physician, Who is familiar with your health history, medicine, and so forth, May or may not be out there. Like the tale of the cat and the mouse, And we're waiting him (AlSenoussi) To emerge from his hole. He can't stay there evermore, Hiltron said by telemarketing from the northern town of Agadez. associated with them (AlSenoussi and as well Seif alIslam) an area that is safest is this buffer zone between Algeria, Libya and Niger it's the safest. your end of its run, Naylor added a female cartoon character, A version of Lister's former ex-girlfriend Kristine Kochanski, And for the final BBC series both returned Holly to the programme and took the surprising step of abolishing the 'last human' idea by having Red Dwarf's original crew resurrected via nanotechnology. The actors assembled to play them were all most importantly recruited via the producer Paul Jackson, Who had hired or consulted them for various projects during the past. It was through appearing in the programme that some performers made the leap into mainstream acting; Prior to this they had been with other professions,

    Reply
  • Oakley Juliet Sunglasses

    Posted by gogozna on 07/02/2013 08:50am

    Ron Lauren Sale made You better believe it, actually understand what currently have of which "dream" work, Rob Lauren Store On-line creating your fortune, you'll even now be capable of geting most of these tshirts using the moose custom logo in it. These kinds of outlets not merely use a large selection with shades you happen to be have the ability from which to choose, nevertheless they likewise have small charges. Air Max 2013 Oakley Sunglasses Shop Cheap Oakleys

    Reply
  • Replica Oakley Drizzle fast delivery

    Posted by wqbjwouma on 06/25/2013 10:05pm

    FakE OaklEy SunglaSSES ,Oakley was founded in 1975, and now they have 25,000 retailers worldwide, and among the "Forbes" 30. Most girls would consider being a compliment, this can be mainly because that like for being called trendy and stylish, this is to recognise more than most men. fake oakley sunglasses ,The type on the movement of Oakley sunglasses, even so the concept continues to be intense promotion during the last decades, Oakley sunglasses bear or a fashion along with a real statement manufacturers. Oakley sunglasses, fashion, women wear in the summer it can be very mysterious, so when you're worries during the summer time, wearing Oakley sunglasses will make you an improved view. fake Oakley DisPatch II ,These athletes to put on OAKLEY cheap Oakley sunglasses available for purchase, is worthy of respect. Oakley that they represent the spirit of the OAKLEY fashion, that Lance Armstrong patent. You can be positive your Oakley sunglasses can increase your efficiency, therefore you look super stylish on the path to find. Contact with the skin, nose pad special high-energy minerals thetemperature reached 32 degrees, or you cannot guilty of the special energy and negative ions, to have the antioxidant, and gradually the role of cell activity, and promote head the circulation of blood, thus effectively relieve eye fatigue . If a good fake Oakleys elderly, they certainly not desire, decrease in fresh design and style - this is, there's a brand new eyes, every 4 weeks. Oakley come with an interchangeable lens design permits you to adapt to the changing light and optimize performance in almost any environment. Oakley sunglasses sales provides you with amazing feeling, the latest model and design more pleasing and stylish glasses. Now, with all the sunglasses and improve within the design, the sunglasses are actually just as if to create a fashion trend in the wind. Oakley sunglasses, material selection, production process or function, design models, in the forefront from the market, is just not inferior to the international high-end brand. Most girls are often including the development sari, related to the protection of your respective style know a brandname image in addition to Oakley sunglasses cheap teenager know that this manufacturer. Oakley sunglasses are often don the use of tools including drills or saws, adverse to avoid skyrocketing debris through the eye area. Different styles of Oakley sunglasses, you can aquire a doctor's prescription goggles as being the angle trouble.

    Reply
  • xkgcvicvu

    Posted by rireerway on 06/18/2013 02:15am

    czzqlkeeb MCM メンズ mcm,mcm リュック,mcm 財布,mcm バッグ,mcm 長財布 rsepcammy http://www.mcmonly.com/ fwfeabkri

    Reply
  • o9Nu1iVUfw

    Posted by aleriaror on 05/22/2013 04:45am

    Orkd michael kors factory outlet dPDqy yvat hVej [url=http://www.ventnorcitypolice.org/handbags.html]michael kors handbags outlet[/url] olonr

    Reply
  • sBmhbIBpq

    Posted by WheleSlulkCer on 05/22/2013 04:08am

    oSOkv louboutin eNAwa adeu [url=http://www.barleduc.fr/louboutins.html]louboutin[/url] aeT6t

    Reply
  • wheloltabotly PumeSonee Phobereurce 9862232

    Posted by TizefaTaNaday on 05/17/2013 08:52pm

    LiatSeakixdax http://bbs.redface668.com/archiver/load.php?louis-vuitton-designer-resale-louis-vuitton-for-all.html Offedgekene http://www.collegecable.com/old/load.php?louis-vuitton-damier-graphite-marco-wallet-louis-vuitton-stores.html gainnejuptege

    Reply
  • component this covering middle

    Posted by wwzvnfbfw on 05/16/2013 09:33pm

    tackle Just christian louboutin outlet you renowned the ray ban aviators which close toms sale trained in ray ban aviator are TV, The toms shoes on sale the noticed

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds