Read the below articles first to understand the AngularJS UI-grid.
Prerequisites
Visual Studio 2017 is the prerequisite to work with this article.
Thus, let's just use the sections with which we can implement the functionality.
- Create ASP.NET MVC 5 Application.
- Adding Model.
- Scaffolding in MVC 5.
- View in MVC 5.
- Log in an Entity Framework.
Create ASP.NET MVC 5 Application
In this section, we'll create an ASP.NET Web Application with the MVC 5 Project Template. Use the procedure given below.
Step 1
Open Visual Studio 2015 and click "New Project".
Step 2
Select "Web" from the left pane and create ASP.NET Web application.
Step 3
Select the MVC Project template in the next ASP.NET wizard.
Visual Studio automatically creates the MVC 5 Application, adds some files and folders to the solution.
Working with Entity Framework
Step 1
Right click on Models folder, click Add New Item, select ADO.NET Entity Data Model from Data template and give a name.
Step 2
Select EF Designer from the database.
Step 3
Make a new connection and select a connection, if you already have a connection.
Step 4
Select tables, view, and stored procedures and click Finish.
Here, you have 2 ways to add Web API class. You can add new Web API controller and select model class and data source that will generate API class with entity framework. Another way is to generate it manually. So in this article, I will create a manual API class.
Model Class
- public class Employee {
- public int EmployeeID {
- get;
- set;
- }
- public string FirstName {
- get;
- set;
- }
- public string LastName {
- get;
- set;
- }
- public string City {
- get;
- set;
- }
- public string Region {
- get;
- set;
- }
- public string PostalCode {
- get;
- set;
- }
- public string Country {
- get;
- set;
- }
- public string Notes {
- get;
- set;
- }
- }
Now, add a builder class.
-
- public NORTHWNDEntities db = new NORTHWNDEntities();
-
-
-
-
- public async Task < IEnumerable < Employee >> GetEmployee() {
- try {
- return await (from n in db.Employees select new Employee {
- EmployeeID = n.EmployeeID,
- FirstName = n.FirstName,
- LastName = n.LastName,
- City = n.City,
- Region = n.Region,
- PostalCode = n.PostalCode,
- Country = n.Country,
- Notes = n.Notes
- }).OrderByDescending(n => n.EmployeeID).ToListAsync();
- } catch (Exception ex) {
- throw ex;
- }
- }
If you want to use a stored procedure, then read my previous article.
Web API
Right click on controller folder, click Add and select Controller and select Web API 2 Controller – Empty.
- [RoutePrefix("api/EmployeeAPI")]
- public class EmployeeAPIController: ApiController {
- private readonly EmployeeVMBuilder _employeeVMBuilder = new EmployeeVMBuilder();
-
- [Route("GetEmployee")]
- public async Task < IEnumerable < Employee >> GetEmployee() {
- return await _employeeVMBuilder.GetEmployee();
- }
- }
Thus, we are done with Entity framework and API Controller here. Now, install the files given below, using "Manage NuGet Package".
Add JavaScript files and CSS reference in BundleConfig.cs.
- bundles.Add(new ScriptBundle("~/bundles/angular").Include(
- "~/Scripts/angular.js",
- "~/Scripts/angular-route.js",
- "~/Scripts/ui-grid.js"));
- bundles.Add(new ScriptBundle("~/bundles/employee").Include(
- "~/Angular/app.js",
- "~/Angular/Services/employeeService.js",
- "~/Angular/Controller/employeeController.js"));
And render on _layout.cshtml.
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- <li>@Html.ActionLink("Home", "Index", "Home")</li>
- <li>@Html.ActionLink("About", "About", "Home")</li>
- <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
- <li>@Html.ActionLink("Employee", "Index", "Employee")</li>
- </ul>
- </div>
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- @Scripts.Render("~/bundles/angular")
- @Scripts.Render("~/bundles/employee")
- @RenderSection("scripts", required: false)
Now, add a new Angular Controller with scope. I am using just one script for Module, Service, and Controller. You can have it separate if working on a big project.
Module
-
- var app = angular.module('app', ['ngRoute', 'ui.grid', 'ui.grid.edit', 'ui.grid.pagination', 'ui.grid.autoResize', 'ui.grid.expandable', 'ui.grid.selection', 'ui.grid.pinning']).config(function($routeProvider, $locationProvider) {
- $locationProvider.hashPrefix('');
- $routeProvider.when('/', {
- templateUrl: 'Home',
- controller: 'homeController'
- }).when('/employee', {
- templateUrl: 'Employee',
- controller: 'employeeController'
- });
-
-
- });
Service- app.service('employeeService', function($http) {
- this.getEmployees = function() {
- var req = $http.get('api/EmployeeAPI/GetEmployee');
- return req;
- };
- });
Controller- app.controller("employeeController", function($scope, $filter, employeeService, $window, $http, $log, $interval) {
- init();
-
- function init() {
-
- employeeService.getEmployees().then(function(result) {
-
-
- $scope.gridOptions.totalItems = result.data.length;
- $scope.totalPage = Math.ceil($scope.gridOptions.totalItems / $scope.pageSize);
- $scope.gridOptions.data = result.data;
- console.log($scope.Employees);
- }, function(error) {
- $window.alert('Oops! Something went wrong while fetching employee data.');
- });
- var paginationOptions = {
- pageNumber: 1,
- pageSize: 10,
- };
- $scope.currentPage = 1;
- $scope.pageSize = paginationOptions.pageSize;
- $scope.gridOptions = {
- enableRowSelection: true,
- selectionRowHeaderWidth: 35,
- enableRowHeaderSelection: true,
-
-
- paginationPageSizes: [$scope.pageSize, $scope.pageSize * 2, $scope.pageSize * 3],
- paginationPageSize: paginationOptions.pageSize,
- enableSorting: true,
- columnDefs: [{
- name: '',
- field: 'EmployeeID',
- enableColumnMenu: false,
- enableHiding: false,
- exporterSuppressExport: true,
- enableSorting: false,
- enableFiltering: false,
- visible: false
- }, {
- name: 'First Name',
- field: 'FirstName',
- headerCellClass: 'tablesorter-header-inner',
- enableFiltering: true,
- enableCellEdit: true,
- }, {
- name: 'Last Name',
- field: 'LastName',
- headerCellClass: 'tablesorter-header-inner',
- enableFiltering: true,
- enableCellEdit: true,
- }, {
- name: 'City',
- field: 'City',
- headerCellClass: 'tablesorter-header-inner',
- enableFiltering: true,
- enableCellEdit: true,
- }, {
- name: 'Region',
- field: 'Region',
- enableCellEdit: false,
- headerCellClass: 'tablesorter-header-inner',
- enableFiltering: true
- }, {
- name: 'Postal Code',
- field: 'PostalCode',
- enableCellEdit: false,
- headerCellClass: 'tablesorter-header-inner',
- enableFiltering: true
- }, {
- name: 'Country',
- field: 'Country',
- enableCellEdit: false,
- headerCellClass: 'tablesorter-header-inner',
- enableFiltering: true
- }, {
- name: 'Notes',
- field: 'Notes',
- enableCellEdit: false,
- headerCellClass: 'tablesorter-header-inner',
- enableFiltering: true
- }],
-
- enableGridMenu: true,
- enableSelectAll: true,
- exporterMenuPdf: false,
- enableFiltering: true,
- exporterCsvFilename: 'EmployeeList_' + $filter('date')(new Date(), 'MM/dd/yyyy') + '.csv',
- exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
- onRegisterApi: function(gridApi) {
- $scope.gridApi = gridApi;
- gridApi.selection.on.rowSelectionChanged($scope, function(row) {
- var msg = 'row selected ' + row.isSelected;
- $log.log(msg);
- console.log(msg);
- $window.alert(msg);
- });
- gridApi.selection.on.rowSelectionChangedBatch($scope, function(rows) {
- var msg = 'rows changed ' + rows.length;
- $log.log(msg);
- $window.alert(msg);
- console.log(msg);
- });
- gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
- debugger;
- paginationOptions.pageNumber = newPage;
- paginationOptions.pageSize = pageSize;
- $scope.pageSize = pageSize;
- $scope.currentPage = newPage;
- $scope.totalPage = Math.ceil($scope.gridOptions.totalItems / $scope.pageSize);
- });
- },
-
-
-
- };
- }
- });
Index- @ {
- ViewBag.Title = "Index";
- Layout = "~/Views/Shared/_Layout.cshtml";
- } < h2 > Employee < /h2> < div ng - controller = "employeeController" > < div ui - grid = "gridOptions"
- ui - grid - pagination
- ui - grid - selection
- ui - grid - exporter
- ui - grid - resize - columns
- ui - grid - auto - resize
- class = "grid" > < /div> < /div>
As everything is done, run the application.
In the given screenshot, you can see the page index and page size. Click "Next" to see the next page index.
Conclusion
In this article, we have seen how to implement paging with Angular UI-Grid with Web API and Entity Framework in MVC. If you have any questions or comments, drop me a line in the comments section.