Tuesday, 18 August 2015

ng-grid with ASP.NET MVC

In this example, we display a table with paging, sorting and searching using ng-grid.

Setting up Northwind Entity Context

After installing the Northwind database, add an Entity Framework Context for it. We are only interested in the `Customers` table.

Ignoring Customer collection properties

Because we will be serializing the `Customer` object to JSON, we need to ensure that the `Orders` and `CustomerDemographics` collections are ignored. Add the following partial class for `Customer` to tell the "Json-izer" to ignore (not attempt to serialize) those properties:

`data` will be the `10` or so records that will be returned as part of the page. `page` is the page number. `pageSize` is the size of the page. `total` is the total number of records. `totalPages` is the total number of pages (so roughly, the `total` divided by the `pageSize`).

Add the following `CustomerServiceController` class. It has a method `GetPage` which will be called by our Javascript when the grid needs to fetch the page data. Note the use of `pageParams` class defined above.

Remember to import the necessary namespaces such as your context's namespace and `System.Linq.Dynamic` and `Newtonsoft.Json`.