Pagination in ASP.Net MVC

I’ve been working on a project using MVC (my first real go around) with Entity Framework providing my model. I’ve been learning a ton of little tricks and I figured I’d better start capturing them now before I lose them or forget. Then 6 months from now I’ll be going, “now where did I have that code that…” LOL

So, to facilitate my own learning curve, I build a very simply database to track my music of interest. I have a table for songs, albums and artists. When displaying Artists, I found that I wanted pagination on the page. I started looking around on the web and found there are tons of different ways of doing it, many that did not make sense to me and none that I tried that actually worked. Therefore, I began working it myself. Here’s how I did it. In the ArtistController (I’ll be doing other posts to explain MVC – if this doesn’t make sense now my apologies. I am handling this topic in a little bit of a scattered way) I added the following Action:

        public ActionResult Paged(int page, int pagesize = 5)
        {
            ViewBag.Page = page;
            ViewBag.PageSize = pagesize;

            int skip = (page - 1) * pagesize;

            var artists = db.Artists
                .OrderBy(c => c.ArtistName)
                .Skip(skip).Take(pagesize);
            return View(artists.ToList());
        }

You can see that this Action takes two parameters, both int. One that represents what page you are on (page) and how many entries are on a page (pagesize). So a 5 and 10 means go to the fifth page where there are ten artists on each page. I pass these values to the ViewBag so I can reference them in the View. I then calculate how far to skip ahead in the model (skip = (page-1)*pagesize). I then use the LINQ statement that says use the Artist model (db represents my EF model with Artists being a class within that model), ordering by artist’s name but that skips the first ‘skip’ artists and takes the next ‘pagesize’ after that. When this LINQ query executes, it will get the artists that I am looking for based on the pagination data provided. Simple right?

Then, in the view that this Action brings up, I used basically the same View that I did for the default Index View and Controller, but I demonstrate how the ViewBag facilitates the exchange of information (i.e. what page the user is on and how many are on a page):

<p>
    On page @ViewBag.Page with a page size of @ViewBag.PageSize.
</p>

My MVC is using the RAZOR engine, making the use of the ViewBag so simple. All that is left (which I haven’t done yet, but will update with when complete) is to build a nice looking control to facilitate the visualization of the paging and including links to flip back and forth on pages like you see in most web apps. The URL to call say the 3rd page of Artists when we are viewing 10 Artists per page looks like:  http://localhost:5027/Artist/Paged/x?page=3&pagesize=10  Artist is the name of my controller. Paged in the Action defined above. And the rest is simply putting the data into the query string. Easy right?  🙂

More to come, but I wanted to document this while I am on it. I’ll be hitting some of the basics and some of the little nuances that I pick up along the way. I’ve found that the tutorials out there (especially those provided by Microsoft) do an excellent job of showing the basics and the norms. But when do our projects stick to the simple and norms? 😉  So I will document some of those other cases in my blog. Hope this helps!

[Updated]

I continued adding features to my paging solution. It turned out to be very easy to do. Most of the solution I saw online were complicated and required third party tools or JavaScript libraries.  My personal thoughts (and feel free to make a case if you think I am mistaken) that using JavaScript to handle paging is counter productive. JavaScript executes client side – why bring too much data to handle over to the client side only to scope it there? Why not let server side dish up the appropriate amount of data? So that’s the approach that I took.

First, one think for me that made the other posts online difficult to follow was the ordering of items. In order to do paging, you have to touch the controller and the view at different points. In cases like these, a picture is worth a thousand words to me. So, to be helpful, here is a picture of the interconnections:

Image of controller and view

Controller and View – click to see larger and clearer

The controller is our starting point for this discussion. The user has come to the controller by entering the appropriate url or through navigations you have provided. The key is the method that it comes to returns an ActionResult. This points the user to the View intended. So we are now off to the View. Inside the view, you may need to facilitate some interaction with the user. For this example, I wanted the user to be able to pick how many log entries were being displayed on the page at a time (hence paging). Now, this selection doesn’t have anything to do with the data model (I am using Entity Framework for this application – if you haven’t used EF, check it out! It is really a great piece of technology. Extremely robust and fun to use! Powerful while being a logical abstraction.) so I really don’t want to cross concerns and implement a page size concept in my model.

What’s needed is a simple HTML form. Notice in the diagram, I have some of the HTML of the View shown. There is a HTML form that contains:

Html.BeginForm("ChosePageSize""CentralLog"FormMethod.Get)

This forms contains a drop down list that enables the user to select pre-fixed page sizes. The first parameter is a string of ChosePageSize. This is the critical part to understand. That string is the name of the method back in the controller that will be called when this form is submitted. The data collected in this form is then available to the controller. Let’s look at the ChosePageSize method in a little detail.

(more coming)

Posted in Entity Framework, Model View Controller (MVC) | Tagged | Leave a comment

The Lotus Team

Check out this cool commercial: http://www.youtube.com/watch?v=rkxJ10PFpHo

Posted in Microsoft | Leave a comment

Bill Gates Unveiled Windo…

Bill Gates Unveiled Windows 30 Years Ago Today

No matter what you think of Windows 8, it’s completely certain that Windows is both iconic and signi…
bingnews://application/view?entitytype=article&pageId=0&contentId=272263444&market=en-us&referrer=share

Quote | Posted on by | Leave a comment

Get SharePoint List Guid via Browser

So, you want (for many possible reasons) to know the GUID that is associated with a List in your SharePoint. Worry not! It is amazingly simple – once you know the trick.
Go to the List and List Settings. Right click on “Title, description and navigation” (see image below).

Then, paste it into your favorite text editor (Notepad, NotePad++, etc). Cut the whole portion after “List=”. What you just cut is the URL encoded GUID for the list! Now use whatever tool you like to decode the value. If you don’t have a tool, check out http://www.albionresearch.com/misc/urlencode.php

And Whamo! You’ve now got the GUID for you list. Piece of cake!
Hope this is helpful.

Posted in General SharePoint, SharePoint Content Management Tips | Leave a comment

A Cool Example of Using Kinect

Check out this cool article: http://www.geekwire.com/2013/kinectcontrolled-water-fountains-student-contest-fluid-challenge/

Gives me some ideas.

Posted in Kinect | Leave a comment

The Martian King

My daughters attended a Microsoft Camp at the Microsoft Store in Tyson’s Corner. At camp, they worked as a team with other kids, wrote a script, captured video, acted out the scenes, researched using the Internet and finally produced a video that they shared with the rest of their campmates. When you watch the video, you may think that it doesn’t make a lot of sense, but keep in mind, this video is 100% the product of the kids in the video. No adults participated directly in its making. The folks at Microsoft taught them how to work it, the kids did the rest. 🙂

Video | Posted on by | Tagged | Leave a comment

Remote Desktop Connection to Hyper-V Virtual Machine

Ok. This one seemed like it should be pretty simple. But I couldn’t find a description of it anywhere online. And I am not the only person who couldn’t figure this out. But I finally figured it out, and it was simple.

Here’s what I have and what I needed: My host machine is Windows 8. I am using Hyper-V (built into Windows 8 – if you are a developer and aren’t using Windows 8, you are missing the boat!) to run a virtual machine (doing some SharePoint development). I frequently need to pass big files back and forth between the host and the virtual. I could never figure out how to do it. I always ended up either emailing the files to myself (because the virtual can see out to the Internet) or storing them up on SkyDrive.

But the other day I had a new need that led me to find the solution. I wanted to use Remote Desktop Connection to connect to the virtual machine. In order to find Remote Desktop Connection in Windows 8, while on the start screen, type ‘mstms’. That will bring up the Remote Desktop Connection (RDC). To make the connection, I would type in the machine name of my virtual. But, after a couple of minutes, it would time out and say that the machine could not be found. I figured that this was a networking issue that I didn’t understand. Well, I found the fix.

On the virtual machine, click on configure remote desktop:

image

and allow connections to the machine. When you do this, you will be prompted to allow the firewall to be changed to permit these connections. Allow it.

Then I realized that by default the type of network is Public. Switch it to Home and enable Sharing. With all that done, you can now use RDC on the host machine to connect into the virtual machine simply by providing the machine name. 

I have an external hard drive connected directly to my router. Now, in the virtual machine, I can explore the network, find the router and connect to the external hard drive. I then created a mapped network drive to it. So I can freely and easily pass files back and forth between by host and virtual. All very easy to do. Just had to get pointed in the right direction.

Hope this helps others!

Posted in General IT, Microsoft | Tagged , , , | 7 Comments