Integrating Angular-Js Grid(ui-grid) with MVC + Web API Call using Angular Js + Pagination ...

Datetime:2016-08-22 23:06:03         Topic: AngularJS          Share        Original >>
Here to See The Original Article!!!


In this article, we will try to understand how to create ASP.NET MVC project, how to create database in SQL Server Management Studio with creating WebApi Project and consuming WebApi by using Angular Js and binding the data to Angular Grid. We are using Entity framework 5.0 as Database Integration tool.

Step 1: Creating ASP.NET MVC Project

  1. Click on VS IDE 2013
  2. New
  3. Project
  4. ASP.NET Web Application

Select MVC template, click on Add button, give name as DemoApp .

Now, you are ready with your MVC project.

Step 2: Create Database and Demo Table Student with Some Data

  1. Open SQL Server Management Studio [Press Windows + R and Enter SSMS ]
  2. Enter your server name (name of your Computer System). Provide your credentials.
    Click on connect.
  3. You will get object explorer panel in SSMS (SQL Server Management Studio).
    Create new database by right clicking on database folder from object explorer and give name as DemoDb .
  4. Click on ok. Now your database is ready.
  5. Create a table into database by clicking on table folder from DemoDb (database).

Below is the script to create table. [Just copy and paste it into your query editor.]

To Create Table

USE [DemoDb]

/****** Object:  Table [dbo].[Student]    Script Date: 23-04-2016 10:26:51 ******/


CREATE TABLE [dbo].[Student](
	[StudentId] [nvarchar](10) NOT NULL,
	[FirstName] [nvarchar](50) NULL,
	[LastName] [nvarchar](50) NULL,
	[Age] [int] NULL,
	[Gender] [nvarchar](50) NULL,
	[Batch] [nvarchar](50) NULL,
	[Address] [nvarchar](50) NULL,
	[Class] [nvarchar](50) NULL,
	[School] [nvarchar](50) NULL,
	[Domicile] [nvarchar](50) NULL,
	[StudentId] ASC


To Insert Data

USE [DemoDb]

INSERT INTO [dbo].[Student]
           '10','Godavari Public School','Sambhajinagar'),
           '10','Hyderabad Public School','Hyderabad'),
           '10','Godavari Public School','Sambhajinagar'),
           '10','A.K Waghmare','Sambhajinagar'),
           '10','Godavari Public School','Sambhajinagar'),
           '10','Godavari Public School','Sambhajinagar'),

Now you have your table ready with you.

Step 3: Adding Entity Data Model into your Web App (Which We Have Created As the First Step)

  1. Right click on Model folder
  2. Add
  3. New Item
  4. In search box, enter Entity Data Model and add it by giving Name as StudentModel .
  5. After clicking on add button, you will see one window, click on EF designer from database and press Next.
  6. After clicking on Next, you have to create new database connection, fill the information required by clicking on New Db connection.
  7. Click on test connection.
    If everything is good, congratulations..!! Go ahead.
  8. You will see window (which will ask about two options to add connection string into web.config or not), check the box to include connection string in web.config and click on next button.
  9. Select required table and click on Finish.
    After clicking on finish, you might get the security warning window, just check on don’t show this message again and click ok.
    Great job... Your model is ready..!!
    Note: To complete this step successfully, you need to install Entity Framework latest version into your project from NuGet Manager.

Step 4: Creating Web API Project in the Same Solution, i.e., DemoApp

  1. Right click on Solution Name
  2. Add
  3. New Project
  4. Select ASP.NET Web app
    Give the Name as DemoApp.Api
  5. Select Web API Template and Click on OK.
    Congratulations... again!! You're ready with your web API.

As you know, we are binding the data from our database DemoDb to Angular Grid into our MVC Application DemoApp by calling Web Api.

So it is required to write some logic to interact with our database DemoDb and performing the required operations.

Add the reference of DemoApp MVC projects with reference to DemoApp.Api .

By right clicking on references => add reference => select required project =>click on Ok.

Note: Please copy the connection string from your DemoApp web.config file and paste it into web.config of DemoApp.Api project.

So, to implement this, follow the below steps:

  1. Right click on Controller Folder into DemoApp.Api project
  2. Add Controller
  3. Select Empty Controller and click on add.
  4. Give name as DemoApiController . Just copy and paste the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace DemoApp.Api.Controllers
    public class DemoApiController : ApiController
        private DemoDbEntities db = new DemoDbEntities();
        public IEnumerable<Student> GetStudents()
            return db.Students.AsEnumerable();
        public IEnumerable<Student> GetStudentsAsc()
            return db.Students.AsEnumerable().OrderBy(x=>x.StudentId);
        public IEnumerable<Student> GetStudentsDesc()
            return db.Students.AsEnumerable().OrderByDescending(x => x.StudentId);

Now, make your DemoApp.Api project as startup project and run the WebApi to see your output.

To see your output in JSON (JavaScript object Notation) format, copy and paste the below code to your WebApiConfig.cs as below:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Congrats..!! Your web API is also ready.

Now, just you have to consume the Web API with its path.

[Path means, the url comes in browser’s address bar after running web API. For example: http://localhost:12345/api/DemoApi/GetStudents ]

Step 5: Consuming Web Api (DempApp.Api) into Web Application (DemoApp)

Now move to DemoApp (MVC web app project):

  1. In DemoApp , right click on Controller folder
  2. Add Controller
  3. Select Empty Controller. Give name as DemoController
  4. Your controller should look like below:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    namespace DemoApp.Controllers
        public class DemoController : Controller
            // GET: Demo
            public ActionResult Index()
                return View();
  5. Right click on Index Action and Add Empty View.
  6. Right click on Scripts folder into DemoApp .
  7. Add new JavaScript file. Give name as App.js and add the below code into it.
    var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.pagination']);
    app.controller('MainCtrl', [
    '$scope', '$http', 'uiGridConstants', function ($scope, $http, uiGridConstants) {
        var paginationOptions = {
            pageNumber: 1,
            pageSize: 10,
            sort: null
        $scope.gridOptions = {
            paginationPageSizes: [10, 20, 30,40,50,60,70,80,90],
            paginationPageSize: 10,
            useExternalPagination: true,
            useExternalSorting: true,
            columnDefs: [
            { name: 'StudentId' },
            { name: 'FirstName', enableSorting: false },
            { name: 'LastName', enableSorting: false },
            { name: 'Age', enableSorting: false },
            { name: 'Gender', enableSorting: false },
            { name: 'Batch', enableSorting: false },
            { name: 'Address', enableSorting: false },
            { name: 'Class', enableSorting: false },
            { name: 'School', enableSorting: false },
            { name: 'Domicile', enableSorting: false },
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
                    if (sortColumns.length == 0) {
                        paginationOptions.sort = null;
                    } else {
                        paginationOptions.sort = sortColumns[0].sort.direction;
                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    paginationOptions.pageNumber = newPage;
                    paginationOptions.pageSize = pageSize;
        var getPage = function () {
            var url;
            switch (paginationOptions.sort) {
                case uiGridConstants.ASC:
    //URL of your Web Api running Path.
                    url = 'http://localhost:57868/api/DemoApi/GetStudentsAsc';
                case uiGridConstants.DESC:
    //URL of your Web Api running Path.
                    url = 'http://localhost:57868/api/DemoApi/GetStudentsDesc';
    //URL of your Web Api running Path.
                    url = 'http://localhost:57868/api/DemoApi/GetStudents';
            .success(function (data) {
                $scope.gridOptions.totalItems = 100;
                var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
                $ = data.slice(firstRow, firstRow + paginationOptions.pageSize);

    After adding the script as App.js into your scripts folder, add the below code into your view, i.e., Index.cshtml .

    <!doctype html>
    <html ng-app="app">
    <script src=""></script> 
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>  
    <script src=""></script>
    <link rel="stylesheet" href="" type="text/css">
                         {   width:auto;
            <div ng-controller="MainCtrl">
                <div ui-grid="gridOptions" ui-grid-pagination class="grid"></div>
            <script src="~/Scripts/App.js"></script>  

Now everything is done.

You just need to do some settings as below:

  1. Set Multiple project Startup to start WebApp(DemoApp) and WebApi(DemoApp.Api)  project parallel.
    1. Right click on solution
    2. Set as startup project
    3. Click on button multiple project
    4. Choose both projects as start.
  2. To give Cross Origin Resource Sharing (CORS)

    Note: [source: wikipedia]

    Cross-origin resource sharing ( CORS ) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the resource originated.

    Need to do the below setting into your WebApi(DemoApp.Api) Projects Web.config file as below:

    Copy and paste this into <System.Webserver> tag into Web.config .

            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  3. With some systems, you will get error for conflicts in Startup.cs file.

    You can resolve the issue by renaming the startup.cs file with some different name at every place in DemoApp.Api project.

Finally, run the project and see your required output.

Points of Interest

Like Angular Grid, we can go with JQuery Grid, but wherever we are having large amount of data, it is good practice to go with Angular Js as it has rich binding capability.


Put your ads here, just $200 per month.