One of my favorite features in the latest release of ASP.NET Web Forms is Model Binding. I always liked it in ASP.NET MVC and it’s great to see it being ported over to Web Forms – and since the model is bound to control values rather than form values, we don’t have the same security concerns as with MVC. The remote user can’t just add new form fields and update more than you intended. (You can fix that in MVC with a white list, but the nice thing about Web Forms is we don’t have to worry about it).
Model binding isn’t just for updates, of course, and recently I found myself using it with a GridView and ListView for display purposes. In the process, I noticed a dearth of online examples showing how to do efficient paging when you’re using Model Binding and methods in the code-behind that call the business layer. So I thought I’d fill the gap.
First off, we need a data access layer to support paging. I like to keep my data access layer as simple as possible and have my logic in a business layer – so the adapter class will simply return IQueryable.:
The adapter is only visible inside my application and I’m never returning the IQueryable beyond the business layer. The business layer contains the logic for pagination (as well as any other necessary logic) and exposes multiple IEnumerable methods, all of which are supported by the underlying IQueryable. Here is a simplified version with the business logic stripped out:
There are two things to note:
We now have a back-end that is capable of supporting efficient pagination. How do we integrate this with UI controls using Model Binding?
I’ve created a ListView and added a DataPager:
When I add a new GetData() method, it creates a stub in the code-behind with an IQueryable return – but also comments advising you how to change it to IEnumerable and which arguments you need to add to support paging.
Here’s the original stub:
And here’s the revised IEnumerable version that calls my business layer object:
And when we run it, we get nice paging using Model Binding via a simple pass-through method in the code-behind that calls our efficient data access code.
And you can use exactly the same techniques (and, in fact, the same method – the arguments are identical) for paging through a GridView.
For other related information, check out this course from Learning Tree: