UI-Grid With AngularJS And WebAPI

UI-Grid

UI-Grid 3.0 (formerly ng-grid) is a 100% Angular grid written with no dependencies other than AngularJS. It is designed around a core grid module and features are layered as Angular modules and Directives. This keeps the core; small and focused, while executing very complex features only when you need them.

In the core module, you get

  • Virtualized rows and columns - only the rows and columns visible in the viewport (+ some extra margin) are actually rendered
  • Bind cells to the complex properties and the functions.
  • Column sorting with three states: Asc, Desc and None.
  • Column filtering.
  • Ability to change the header and the cell contents with the custom templates.
  • i18nService allows label translations.

Prerequisites

Visual Studio 2015 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 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 the 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 an Entity Framework

Follow the steps given below.

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, stored procedures and click Finish.

 

Now, create a new Web API controller with actions, using Entity Framework, as shown below.

Step 1

Right click on controller folder, click Add and select Controller.

Step 2

Select Web API Controller with actions, using Entity Framework.

Step 3

Select Model Class, Data context class, controller name and click Add.

You will get the code given below. 

  1. using ng_ui_grid_sample.Models;  
  2. using System.Data.Entity;  
  3. using System.Data.Entity.Infrastructure;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Threading.Tasks;  
  7. using System.Web.Http;  
  8. using System.Web.Http.Description;  
  9. namespace ng_ui_grid_sample.Controllers {  
  10.     public class EmployeesAPIController: ApiController {  
  11.         private NORTHWNDEntities db = new NORTHWNDEntities();  
  12.         // GET: api/Employees    
  13.         public IQueryable < Employees > GetEmployees() {  
  14.             return db.Employees;  
  15.         }  
  16.         // GET: api/Employees/5    
  17.         [ResponseType(typeof(Employees))]  
  18.         public async Task < IHttpActionResult > GetEmployees(int id) {  
  19.             Employees employees = await db.Employees.FindAsync(id);  
  20.             if (employees == null) {  
  21.                 return NotFound();  
  22.             }  
  23.             return Ok(employees);  
  24.         }  
  25.         // PUT: api/Employees/5    
  26.         [ResponseType(typeof(void))]  
  27.         public async Task < IHttpActionResult > PutEmployees(int id, Employees employees) {  
  28.             if (!ModelState.IsValid) {  
  29.                 return BadRequest(ModelState);  
  30.             }  
  31.             if (id != employees.EmployeeID) {  
  32.                 return BadRequest();  
  33.             }  
  34.             db.Entry(employees).State = EntityState.Modified;  
  35.             try {  
  36.                 await db.SaveChangesAsync();  
  37.             } catch (DbUpdateConcurrencyException) {  
  38.                 if (!EmployeesExists(id)) {  
  39.                     return NotFound();  
  40.                 } else {  
  41.                     throw;  
  42.                 }  
  43.             }  
  44.             return StatusCode(HttpStatusCode.NoContent);  
  45.         }  
  46.         // POST: api/Employees    
  47.         [ResponseType(typeof(Employees))]  
  48.         public async Task < IHttpActionResult > PostEmployees(Employees employees) {  
  49.             if (!ModelState.IsValid) {  
  50.                 return BadRequest(ModelState);  
  51.             }  
  52.             db.Employees.Add(employees);  
  53.             await db.SaveChangesAsync();  
  54.             return CreatedAtRoute("DefaultApi"new {  
  55.                 id = employees.EmployeeID  
  56.             }, employees);  
  57.         }  
  58.         // DELETE: api/Employees/5    
  59.         [ResponseType(typeof(Employees))]  
  60.         public async Task < IHttpActionResult > DeleteEmployees(int id) {  
  61.             Employees employees = await db.Employees.FindAsync(id);  
  62.             if (employees == null) {  
  63.                 return NotFound();  
  64.             }  
  65.             db.Employees.Remove(employees);  
  66.             await db.SaveChangesAsync();  
  67.             return Ok(employees);  
  68.         }  
  69.         protected override void Dispose(bool disposing) {  
  70.             if (disposing) {  
  71.                 db.Dispose();  
  72.             }  
  73.             base.Dispose(disposing);  
  74.         }  
  75.         private bool EmployeesExists(int id) {  
  76.             return db.Employees.Count(e => e.EmployeeID == id) > 0;  
  77.         }  
  78.     }  
  79. }    

Thus, we are done with an Entity framework and API controller here. Now, install the files given below, using Manage NuGet Package. Manager.

Add JavaScript files and CSS reference in BundleConfig.cs.

  1. bundles.Add(new StyleBundle("~/Content/css").Include(  
  2. "~/Content/bootstrap.css",  
  3. "~/Content/site.css",  
  4. "~/Content/ui-grid.css"));  
  5. bundles.Add(new ScriptBundle("~/bundles/uigrid").Include(  
  6. "~/Scripts/ui-grid.min.js"));  
  7. bundles.Add(new ScriptBundle("~/bundles/angular").Include(  
  8. "~/Scripts/angular.min.js",  
  9. "~/Angular/Controller/employeecontroller.js"));   

And render on _layout.cshtml. 

  1. @Scripts.Render("~/bundles/jquery")  
  2. @Scripts.Render("~/bundles/bootstrap")  
  3. @Scripts.Render("~/bundles/angular")  
  4. @Scripts.Render("~/bundles/uigrid")  
  5. @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

  1. var employeeapp = angular.module('employeeapp', ['ui.grid''ui.grid.pagination']);   

Service 

  1. employeeapp.service("employeeservice", function ($http) {  
  2. //Function to call get genre web api call  
  3. this.GetEmployee = function () {  
  4. var req = $http.get('api/EmployeesAPI');  
  5. return req;  
  6. }  
  7. });   

Controller 

  1. employeeapp.controller("employeecontroller"function($scope, employeeservice, $filter, $window) {  
  2.     GetEmployee();  
  3.   
  4.     function GetEmployee() {  
  5.         debugger  
  6.         employeeservice.GetEmployee().then(function(result) {  
  7.             $scope.Employees = result.data;  
  8.             console.log($scope.Employees);  
  9.         }, function(error) {  
  10.             $window.alert('Oops! Something went wrong while fetching genre data.');  
  11.         })  
  12.     }  
  13.     //Used to bind ui-grid    
  14.     $scope.selectedItem = null;  
  15.     $scope.gridOptions = {  
  16.         enableRowSelection: true,  
  17.         paginationPageSizes: [5, 10, 20, 30, 40],  
  18.         paginationPageSize: 10,  
  19.         enableSorting: true,  
  20.         columnDefs: [{  
  21.             name: 'photo',  
  22.             enableSorting: false,  
  23.             field: 'PhotoPath',  
  24.             cellTemplate: "<img width=\"50px\" ng-src=\"{{grid.getCellValue(row, col)}}\" lazy-src>"  
  25.         }, {  
  26.             name: 'First Name',  
  27.             field: 'FirstName',  
  28.             headerCellClass: 'tablesorter-header-inner'  
  29.         }, {  
  30.             name: 'Last Name',  
  31.             field: 'LastName',  
  32.             headerCellClass: 'tablesorter-header-inner'  
  33.         }, {  
  34.             name: 'Title',  
  35.             field: 'Title',  
  36.             headerCellClass: 'tablesorter-header-inner'  
  37.         }, {  
  38.             name: 'City',  
  39.             field: 'City',  
  40.             headerCellClass: 'tablesorter-header-inner'  
  41.         }, {  
  42.             name: 'Country',  
  43.             field: 'Country',  
  44.             headerCellClass: 'tablesorter-header-inner'  
  45.         }, {  
  46.             name: 'Notes',  
  47.             field: 'Notes',  
  48.             headerCellClass: 'tablesorter-header-inner'  
  49.         }],  
  50.         data: 'Employees'  
  51.     };  
  52. });  

Now, let’s work on an Index page. 

  1. @{  
  2.   
  3. ViewBag.Title = "Index";  
  4.   
  5. Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <h2>Employee</h2>  
  9.   
  10.    <div ng-app="employeeapp" ng-controller="employeecontroller">  
  11.   
  12.    <div ui-grid="gridOptions" ui-grid-pagination ui-grid-selection class="grid" ui-grid-auto-resize>  
  13.   
  14.    </div>  
  15.   
  16. </div>   

As everything is done, run the Application.



You can see this grid is fully featured with paging sorting and many more features.

 

You can sort ascending and descending and you can hide the column as well.

Paging looks cool. Doesn't it? 

Conclusion

In this article, we have seen how to use Angular UI-Grid with Web API with an Entity Framework in MVC. If you have any question or comments, drop me a line in the comments section.