charlie_cat
charlie_cat

Reputation: 1850

Pagination in asp.net mvc3 where list is from directory entries

The list I have to paginate is actually entries in a directory. i dont get data from the db. my controller part:

public ActionResult Index()
{
  // Iterate over all folders in the SCORM folder to find training material

  UrlHelper urlHelper = new UrlHelper(HttpContext.Request.RequestContext);
  string scormRelativePath = urlHelper.Content("~/ScormPackages");
  string scormRootDir = HttpContext.Server.MapPath(scormRelativePath);
  string scormSchemaVersion = string.Empty;
  string scormTitle = string.Empty;
  string scormDirectory = string.Empty;
  string scormEntryPointRef = string.Empty;
  string scormIdentifierRef = string.Empty;
  Int16 scormLaunchHeight = 640;
  Int16 scormLaunchWidth = 990;
  bool scormLaunchResize = false;
  string scormRelativeHtmlPath = string.Empty;


  List<ScormModuleInfo> modules = new List<ScormModuleInfo>();

  foreach (var directory in Directory.EnumerateDirectories(scormRootDir))
  {
    ScormModuleInfo module = new ScormModuleInfo();
    //more code
  }  
 }

in my view:

   <% int idx = 0;
   foreach (var module in Model)
   { %>
      //lists names of the folders in the ScormPackages directory
   }

enter image description here

so how will I handle pagination in this case please?

thanks

Upvotes: 0

Views: 156

Answers (1)

Benjamin Gale
Benjamin Gale

Reputation: 13177

You can paginate your list by using the Skip and Take extension methods of the Enumerable class on your modules list.

Below is a complete console application demonstrating how to do this:

class Program
{
    static void Main(string[] args)
    {
        IList<string> lst = new List<string>
        {
            "One",
            "Two",
            "Three",
            "Four",
            "Five",
            "Six",
            "Seven",
            "Eight",
            "Nine",
            "Ten",
        };

        int pageSize = 3;
        int page = 2;

        var pagedLst = lst
                       .Skip((page - 1) * pageSize)
                       .Take(pageSize);

        foreach (string item in pagedLst)
        {
            Console.WriteLine(item);
        }
    }
}

I would do the paging and sorting in your controllers action methods and pass the sorted list to the view which would leave your view code untouched (your view shouldn't really be doing the paging and sorting itself).

The code in your action method would look something like this:

List<ScormModuleInfo> modules = new List<ScormModuleInfo>();

var pagedModules = modules
                   .Skip((page - 1) * pageSize)
                   .Take(pageSize);

Upvotes: 1

Related Questions