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.
- using ng_ui_grid_sample.Models;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Linq;
- using System.Net;
- using System.Threading.Tasks;
- using System.Web.Http;
- using System.Web.Http.Description;
- namespace ng_ui_grid_sample.Controllers {
- public class EmployeesAPIController: ApiController {
- private NORTHWNDEntities db = new NORTHWNDEntities();
-
- public IQueryable < Employees > GetEmployees() {
- return db.Employees;
- }
-
- [ResponseType(typeof(Employees))]
- public async Task < IHttpActionResult > GetEmployees(int id) {
- Employees employees = await db.Employees.FindAsync(id);
- if (employees == null) {
- return NotFound();
- }
- return Ok(employees);
- }
-
- [ResponseType(typeof(void))]
- public async Task < IHttpActionResult > PutEmployees(int id, Employees employees) {
- if (!ModelState.IsValid) {
- return BadRequest(ModelState);
- }
- if (id != employees.EmployeeID) {
- return BadRequest();
- }
- db.Entry(employees).State = EntityState.Modified;
- try {
- await db.SaveChangesAsync();
- } catch (DbUpdateConcurrencyException) {
- if (!EmployeesExists(id)) {
- return NotFound();
- } else {
- throw;
- }
- }
- return StatusCode(HttpStatusCode.NoContent);
- }
-
- [ResponseType(typeof(Employees))]
- public async Task < IHttpActionResult > PostEmployees(Employees employees) {
- if (!ModelState.IsValid) {
- return BadRequest(ModelState);
- }
- db.Employees.Add(employees);
- await db.SaveChangesAsync();
- return CreatedAtRoute("DefaultApi", new {
- id = employees.EmployeeID
- }, employees);
- }
-
- [ResponseType(typeof(Employees))]
- public async Task < IHttpActionResult > DeleteEmployees(int id) {
- Employees employees = await db.Employees.FindAsync(id);
- if (employees == null) {
- return NotFound();
- }
- db.Employees.Remove(employees);
- await db.SaveChangesAsync();
- return Ok(employees);
- }
- protected override void Dispose(bool disposing) {
- if (disposing) {
- db.Dispose();
- }
- base.Dispose(disposing);
- }
- private bool EmployeesExists(int id) {
- return db.Employees.Count(e => e.EmployeeID == id) > 0;
- }
- }
- }
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.
- bundles.Add(new StyleBundle("~/Content/css").Include(
- "~/Content/bootstrap.css",
- "~/Content/site.css",
- "~/Content/ui-grid.css"));
- bundles.Add(new ScriptBundle("~/bundles/uigrid").Include(
- "~/Scripts/ui-grid.min.js"));
- bundles.Add(new ScriptBundle("~/bundles/angular").Include(
- "~/Scripts/angular.min.js",
- "~/Angular/Controller/employeecontroller.js"));
And render on _layout.cshtml.
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- @Scripts.Render("~/bundles/angular")
- @Scripts.Render("~/bundles/uigrid")
- @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 employeeapp = angular.module('employeeapp', ['ui.grid', 'ui.grid.pagination']);
Service
- employeeapp.service("employeeservice", function ($http) {
-
- this.GetEmployee = function () {
- var req = $http.get('api/EmployeesAPI');
- return req;
- }
- });
Controller
- employeeapp.controller("employeecontroller", function($scope, employeeservice, $filter, $window) {
- GetEmployee();
-
- function GetEmployee() {
- debugger
- employeeservice.GetEmployee().then(function(result) {
- $scope.Employees = result.data;
- console.log($scope.Employees);
- }, function(error) {
- $window.alert('Oops! Something went wrong while fetching genre data.');
- })
- }
-
- $scope.selectedItem = null;
- $scope.gridOptions = {
- enableRowSelection: true,
- paginationPageSizes: [5, 10, 20, 30, 40],
- paginationPageSize: 10,
- enableSorting: true,
- columnDefs: [{
- name: 'photo',
- enableSorting: false,
- field: 'PhotoPath',
- cellTemplate: "<img width=\"50px\" ng-src=\"{{grid.getCellValue(row, col)}}\" lazy-src>"
- }, {
- name: 'First Name',
- field: 'FirstName',
- headerCellClass: 'tablesorter-header-inner'
- }, {
- name: 'Last Name',
- field: 'LastName',
- headerCellClass: 'tablesorter-header-inner'
- }, {
- name: 'Title',
- field: 'Title',
- headerCellClass: 'tablesorter-header-inner'
- }, {
- name: 'City',
- field: 'City',
- headerCellClass: 'tablesorter-header-inner'
- }, {
- name: 'Country',
- field: 'Country',
- headerCellClass: 'tablesorter-header-inner'
- }, {
- name: 'Notes',
- field: 'Notes',
- headerCellClass: 'tablesorter-header-inner'
- }],
- data: 'Employees'
- };
- });
Now, let’s work on an Index page.
- @{
-
- ViewBag.Title = "Index";
-
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <h2>Employee</h2>
-
- <div ng-app="employeeapp" ng-controller="employeecontroller">
-
- <div ui-grid="gridOptions" ui-grid-pagination ui-grid-selection class="grid" ui-grid-auto-resize>
-
- </div>
-
- </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.