Steps To Perform CRUD Operations Using AngularJS And Stored Procedure In An ASP.NET MVC

Introduction

AngularJS is an MVC based framework. Google developed AngularJS. AngularJS is an open source project, which can be used freely, modified and shared by others.

Top features Of AngularJS

  1. Two Way Data-Binding
    This means that any changes to the model updates the view and any changes to the view updates the model.
  1. Dependency Injection
    AngularJS has a built-in Dependency Injection, which makes application easier to develop, maintain and debug in addition to the test.
  1. Testing
    Angular will test any of its code through both unit testing and end-to-end testing.
  1. Model View Controller
    Split your application into MVC components. Maintaining these components and connecting them together means setting up Angular.

To build AngularJS Applications, you should download the script file and it is angular.js. To get the script file, visit https://angularjs.org

Angular MVC

In AngularJS, MVC is implemented in JavaScript and HTML. The view is defined in an HTML form, while the model and controller are implemented in JavaScript. There are several methods by which these components can be put together in AngularJS. 

Views

View in an AngularJS application is created with an HTML. The body of HTML that makes up View will be stored in separate files. 

Directives In AngularJS

AngularJS directives are used in HTML.

  • ng-app − Starts an AngularJS Application.
  • ng-init − Initializes the Application data.
  • ng-model − Binds the values of AngularJS Application data to HTML input controls.
  • ng-repeat − Repeats HTML elements for each item in a collection. 

Controllers in an AngularJS

AngularJS application has controllers to control the flow of data in the application. A Controller is controlled, using ng-controller directive. A controller is a JavaScript object, which contains attributes, properties and functions. Each Controller accepts $scope as a parameter , which refers to the application module that the controller is to control.

Filters In AngularJS

Filters are used to modify the data and can be used in an expression or Directives using pipe character.

  1. uppercase converts  text to upper case text.
  2. lowercase converts text  to lower case text.
  3. currency formats text  in a currency format.
  4. filter- It filters the array to a subset of it based on its provided criteria.
  5. order by- It orders the array based on its provided criteria. 

Module In AngularJS

Modules are used to separate Services, Controllers, Application etc. We define modules in separate JS files. Two types of modules are give below.

  • Application Module − It is used to initialize an application with controller(s).
  • Controller Module − It is used to define Controller.

Scope In AngularJS

Scope is a JavaScript object, which plays the role of joining Controller with the Views. Scope contains the model data. In Controllers, model data is accessed via $scope object.

$scope is passed as a first argument to controller.$scope.message and $scope.type are the models, which are to be used in an HTML page. We have set the values to models, which will be reflected in the application module. We can define the functions as well in $scope.

Custom Directives in AngularJS

Custom Directives are used in AngularJS to enhance the functionality of HTML. Custom Directives are defined, using Directive function. AngularJS application during Bootstrap finds the matching elements and does a one time activity, using its compile() method of the custom Directive. It then processes the element, using link() method of the custom Directive, which is based on the scope of Directive.

Types of Custom Directives

Element Directives activate when a matching element is encountered. Attribute Directive activates when a matching attribute is encountered. CSS Directive activates when a matching CSS style is encountered. Comment Directive activates when a matching comment is encountered.

Internationalization In AngularJS

AngularJS supports an inbuilt internationalization for three types of filters: currency, date and numbers. We only need to use corresponding JS according to locale of the country. By default, it will take the locale of the Browser.

Includes in AngularJS

To achieve embedded HTML pages inside HTML page functionality, the following ways are used − using AJAX. Make a Server call to get the corresponding HTML page and set it in an inner HTML of HTML control. Using Server side Includes JSP, PHP and other Web site Server technologies can include HTML pages. Using AngularJS, we can embed HTML pages within a HTML page, using ng-include Directive. 

AJAX In AngularJS

AngularJS provides $https: control, which works as a Service to retrieve the data from the Server. The Server makes a database call to get the required records. AngularJS needs data in JSON format. Once the data is ready, $https can be used to get the data from the Server. 

Steps to build AngularJs Mvc app to perform Crud functionality.

Step 1

First create an ASP.NET MVC 4 Application named “SatyaAngularjsWebApi”.

Asp.net

Step 2

Now, create a MDF file named “Database1.mdf” inside App_Data folder.

Asp.net

Step 3

Now, create one table and single stored procedure to perform Crud functionality .

Table Script 

  1. CREATE TABLE[dbo].[Employee](  
  2.     [Id] INT IDENTITY(1, 1) NOT NULL, [Name] NVARCHAR(50) NOT NULL, [Address] NVARCHAR(50) NOT NULL, [Country] NVARCHAR(50) NOT NULL, [City] NVARCHAR(50) NOT NULL, [Mobile] NVARCHAR(10) NOT NULLPRIMARY KEY CLUSTERED([Id] ASC));   

 Asp.net

Stored Procedure Script 

  1. CREATE PROCEDURE sp_InsUpdDelEmployee  
  2. @id int,  
  3. @name nvarchar(50),  
  4.     @address nvarchar(50),  
  5.     @country nvarchar(50),  
  6.     @city nvarchar(50),  
  7.     @mobile nvarchar(50),  
  8.     @type varchar(10)  
  9. AS  
  10. Begin  
  11. if (@type = 'Ins'Begin  
  12. insert into Employee  
  13. values(@name, @address, @country, @city, @mobile)  
  14. End  
  15. if (@type = 'Upd'Begin  
  16. update Employee  
  17. set Name = @name, [Address] = @address,  
  18.     Country = @country,  
  19.     City = @city,  
  20.     Mobile = @mobile  
  21. where Id = @id  
  22. End  
  23. if (@type = 'Del'Begin  
  24. delete from Employee  
  25. where Id = @id  
  26. End  
  27. if (@type = 'GetById'Begin  
  28. select * from Employee  
  29. where Id = @id  
  30. End  
  31. select * from Employee  
  32. End   

Stored Procedure Script description

I have added 4 different types, using @type parameter to perform CRUD operation.

For Insert 

  1. if (@type = 'Ins'Begin  
  2. insert into Employee  
  3. values(@name, @address, @country, @city, @mobile)  
  4. End   

For Update 

  1. if (@type = 'Upd'Begin  
  2. update Employee  
  3. set Name = @name, [Address] = @address,  
  4.     Country = @country,  
  5.     City = @city,  
  6.     Mobile = @mobile  
  7. where Id = @id  
  8. End   

For Delete 

  1. if (@type = 'Del'Begin  
  2. delete from Employee  
  3. where Id = @id  
  4. End   

For Get By Id 

  1. if (@type = 'GetById'Begin  
  2. select * from Employee  
  3. where Id = @id  
  4. End  
  5. select * from Employee  
  6. End  

Asp.net

There is no need to create connection string in web.config file. It can be run anywhere any time.

All systems generate the connection string in Web.Config file.

Code Ref 

  1. <connectionStrings>  
  2.     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-SatyaAngularjsWebApi-20170324113216;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-SatyaAngularjsWebApi-20170324113216.mdf" providerName="System.Data.SqlClient" />  
  3.     <add name="Database1Entities" connectionString="metadata=res://*/Models.Model.csdl|res://*/Models.Model.ssdl|res://*/Models.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />   
  4. </connectionStrings>   

Asp.net 

Step 4

Create a Controller class file named “EmployeeAPIController.cs”.

Asp.net

Code Ref 

  1. using SatyaAngularjsWebApi.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Web.Http;  
  8. using System.Data;  
  9. using System.Data.Entity.Infrastructure;  
  10. namespace SatyaAngularjsWebApi {  
  11.     public class EmployeeAPIController: ApiController {  
  12.         // Get All The Employee  
  13.         [HttpGet]  
  14.         public List < Employee > Get() {  
  15.             List < Employee > emplist = new List < Employee > ();  
  16.             using(Database1Entities db = new Database1Entities()) {  
  17.                 var results = db.sp_InsUpdDelEmployee(0, """""""""""Get").ToList();  
  18.                 foreach(var result in results) {  
  19.                     var employee = new Employee() {  
  20.                         Id = result.Id,  
  21.                             Name = result.Name,  
  22.                             Address = result.Address,  
  23.                             Country = result.Country,  
  24.                             City = result.City,  
  25.                             Mobile = result.Mobile  
  26.                     };  
  27.                     emplist.Add(employee);  
  28.                 }  
  29.                 return emplist;  
  30.             }  
  31.         }  
  32.         // Get Employee By Id  
  33.         public Employee Get(int id) {  
  34.             using(Database1Entities db = new Database1Entities()) {  
  35.                 Employee employee = db.Employees.Find(id);  
  36.                 if (employee == null) {  
  37.                     throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));  
  38.                 }  
  39.                 return employee;  
  40.             }  
  41.         }  
  42.         // Insert Employee  
  43.         public HttpResponseMessage Post(Employee employee) {  
  44.             if (ModelState.IsValid) {  
  45.                 using(Database1Entities db = new Database1Entities()) {  
  46.                     var emplist = db.sp_InsUpdDelEmployee(0, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Ins").ToList();  
  47.                     HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, emplist);  
  48.                     return response;  
  49.                 }  
  50.             } else {  
  51.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);  
  52.             }  
  53.         }  
  54.         // Update Employee  
  55.         public HttpResponseMessage Put(Employee employee) {  
  56.             List < sp_InsUpdDelEmployee_Result > emplist = new List < sp_InsUpdDelEmployee_Result > ();  
  57.             if (!ModelState.IsValid) {  
  58.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);  
  59.             }  
  60.             using(Database1Entities db = new Database1Entities()) {  
  61.                 try {  
  62.                     emplist = db.sp_InsUpdDelEmployee(employee.Id, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Upd").ToList();  
  63.                 } catch (DbUpdateConcurrencyException ex) {  
  64.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);  
  65.                 }  
  66.             }  
  67.             return Request.CreateResponse(HttpStatusCode.OK, emplist);  
  68.         }  
  69.         // Delete employee By Id  
  70.         public HttpResponseMessage Delete(int id) {  
  71.             using(Database1Entities db = new Database1Entities()) {  
  72.                 List < sp_InsUpdDelEmployee_Result > emplist = new List < sp_InsUpdDelEmployee_Result > ();  
  73.                 var results = db.sp_InsUpdDelEmployee(id, """""""""""GetById").ToList();  
  74.                 if (results.Count == 0) {  
  75.                     return Request.CreateResponse(HttpStatusCode.NotFound);  
  76.                 }  
  77.                 try {  
  78.                     emplist = db.sp_InsUpdDelEmployee(id, """""""""""Del").ToList();  
  79.                 } catch (DbUpdateConcurrencyException ex) {  
  80.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);  
  81.                 }  
  82.                 return Request.CreateResponse(HttpStatusCode.OK, emplist);  
  83.             }  
  84.         }  
  85.         // Prevent Memory Leak  
  86.         protected override void Dispose(bool disposing) {  
  87.             using(Database1Entities db = new Database1Entities())  
  88.             db.Dispose();  
  89.             base.Dispose(disposing);  
  90.         }  
  91.     }  
  92. }   

Code description 

We have to add the following namespaces to create the functionality in MVC, using AngularJS and WebAPI.

  1. using System.Net;  
  2. using System.Net.Http;  
  3. using System.Web.Http;  
  4. using System.Data;  
  5. using System.Data.Entity.Infrastructure;   

To get all the employees, write the code, as shown below.

  1. [HttpGet]  
  2. public List < Employee > Get() {  
  3.     List < Employee > emplist = new List < Employee > ();  
  4.     using(Database1Entities db = new Database1Entities()) {  
  5.         var results = db.sp_InsUpdDelEmployee(0, """""""""""Get").ToList();  
  6.         foreach(var result in results) {  
  7.             var employee = new Employee() {  
  8.                 Id = result.Id,  
  9.                     Name = result.Name,  
  10.                     Address = result.Address,  
  11.                     Country = result.Country,  
  12.                     City = result.City,  
  13.                     Mobile = result.Mobile  
  14.             };  
  15.             emplist.Add(employee);  
  16.         }  
  17.         return emplist;  
  18.     }  
  19. }   

Here, Database1Entities is a Auto generate model class file, which is related with Database1.mdf file.

This class helps us to connect to the Data Source and perform Insert, Update, Delete, Retrieve operation. 

  1. List<Employee> emplist = new List<Employee>();   

Here, Employee name of the table acts as a list generic class. 

  1. var results = db.sp_InsUpdDelEmployee(0, """""""""""Get").ToList();   

Here, “sp_InsUpdDelEmployee” is the name of the procedure. 

To get employee by Id, follow the code given below. 

  1. public Employee Get(int id) {  
  2.     using(Database1Entities db = new Database1Entities()) {  
  3.         Employee employee = db.Employees.Find(id);  
  4.         if (employee == null) {  
  5.             throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));  
  6.         }  
  7.         return employee;  
  8.     }  
  9. }   

Here, an id is the name of the column.

To insert New Employee details, follow the code given below. 

  1. public HttpResponseMessage Post(Employee employee) {  
  2.     if (ModelState.IsValid) {  
  3.         using(Database1Entities db = new Database1Entities()) {  
  4.             var emplist = db.sp_InsUpdDelEmployee(0, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Ins").ToList();  
  5.             HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, emplist);  
  6.             return response;  
  7.         }  
  8.     } else {  
  9.         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);  
  10.     }  
  11. }   

Here, “Ins” type, mention using stored procedure.

var emplist = db.sp_InsUpdDelEmployee(0, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Ins").ToList();

To update the existing employee, follow the code given below. 

  1. public HttpResponseMessage Put(Employee employee) {  
  2.     List < sp_InsUpdDelEmployee_Result > emplist = new List < sp_InsUpdDelEmployee_Result > ();  
  3.     if (!ModelState.IsValid) {  
  4.         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);  
  5.     }  
  6.     using(Database1Entities db = new Database1Entities()) {  
  7.         try {  
  8.             emplist = db.sp_InsUpdDelEmployee(employee.Id, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Upd").ToList();  
  9.         } catch (DbUpdateConcurrencyException ex) {  
  10.             return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);  
  11.         }  
  12.     }  
  13.     return Request.CreateResponse(HttpStatusCode.OK, emplist);  
  14. }   

Here “Upd” type is mentioned, using stored procedure.

To delete an employee by Id, proceed as shown below. 

  1. public HttpResponseMessage Delete(int id) {  
  2.     using(Database1Entities db = new Database1Entities()) {  
  3.         List < sp_InsUpdDelEmployee_Result > emplist = new List < sp_InsUpdDelEmployee_Result > ();  
  4.         var results = db.sp_InsUpdDelEmployee(id, """""""""""GetById").ToList();  
  5.         if (results.Count == 0) {  
  6.             return Request.CreateResponse(HttpStatusCode.NotFound);  
  7.         }  
  8.         try {  
  9.             emplist = db.sp_InsUpdDelEmployee(id, """""""""""Del").ToList();  
  10.         } catch (DbUpdateConcurrencyException ex) {  
  11.             return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);  
  12.         }  
  13.         return Request.CreateResponse(HttpStatusCode.OK, emplist);  
  14.     }  
  15. }   

Here, “GetById” type is mentioned to take the particular employee data. Here, “Del” type is mentioned, using stored procedure.

To prevent Memory Leak here, use Dispose method. 

  1. protected override void Dispose(bool disposing) {  
  2.     using(Database1Entities db = new Database1Entities())  
  3.     db.Dispose();  
  4.     base.Dispose(disposing);  
  5. }   

Asp.net 

Step 5

Here, I will check the Model created create “Database1.mdf” file, using ADO.NET Entity Data Model.

You can check here the Auto Generate class or the database entity generated here. The Database1Entities with the table and stored procedure are given below.

Asp.net

Also, you can get Employee.Cs file inside Model class folder.

Asp.net

The name of ADO.NET Entity Data Model file is Model.edmx.

Asp.net

Step 6

Create another controller class file named TestController.cs to create one View.

Code Ref 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. namespace SatyaAngularjsWebApi {  
  7.     public class TestController: Controller {  
  8.         public ActionResult Index() {  
  9.             return View();  
  10.         }  
  11.     }  
  12. }   

Code decription

Here, Index Controller action method is used to create one cshtml file i.e. action result returns type. 

Asp.net 

Step 7

Add a “bootstrap.css” reference file inside CSS folder to operate layout and design in AngularJS. It can be used as reference class in view cshtml file.

Asp.net

Step 8

Here, I have added one angular.js reference file inside JS folder. Here, all AngularJS related Directives, scope, functionalities and filters are mentioned here. Hence, all built in functionality of AngularJS will be handled by this JS file.

Asp.net

Step 9

Here, I have created one JS file for joining controller with the views, using $scope object.

Code Ref 

  1. var app = angular.module('myApp', []);  
  2. app.controller('employeeController', ['$scope''$http', employeeController]);  
  3.   
  4. function employeeController($scope, $http) {  
  5.     $scope.loading = true;  
  6.     $scope.updateShow = false;  
  7.     $scope.addShow = true;  
  8.     $http.get('/api/EmployeeAPI/').success(function(data) {  
  9.         $scope.employees = data;  
  10.     }).error(function() {  
  11.         $scope.error = "An Error has occured while loading posts!";  
  12.     });  
  13.     $scope.add = function() {  
  14.         $scope.loading = true;  
  15.         $http.post('/api/EmployeeAPI/'this.newemployee).success(function(data) {  
  16.             $scope.employees = data;  
  17.             $scope.updateShow = false;  
  18.             $scope.addShow = true;  
  19.             $scope.newemployee = '';  
  20.         }).error(function(data) {  
  21.             $scope.error = "An Error has occured while Saving employee! " + data;  
  22.         });  
  23.     }  
  24.     $scope.edit = function() {  
  25.         var Id = this.employee.Id;  
  26.         $http.get('/api/EmployeeAPI/' + Id).success(function(data) {  
  27.             $scope.newemployee = data;  
  28.             $scope.updateShow = true;  
  29.             $scope.addShow = false;  
  30.         }).error(function() {  
  31.             $scope.error = "An Error has occured while loading posts!";  
  32.         });  
  33.     }  
  34.     $scope.update = function() {  
  35.         $scope.loading = true;  
  36.         console.log(this.newemployee);  
  37.         $http.put('/api/EmployeeAPI/'this.newemployee).success(function(data) {  
  38.             $scope.employees = data;  
  39.             $scope.updateShow = false;  
  40.             $scope.addShow = true;  
  41.             $scope.newemployee = '';  
  42.         }).error(function(data) {  
  43.             $scope.error = "An Error has occured while Updating employee! " + data;  
  44.         });  
  45.     }  
  46.     $scope.delete = function() {  
  47.         var Id = this.employee.Id;  
  48.         $scope.loading = true;  
  49.         $http.delete('/api/EmployeeAPI/' + Id).success(function(data) {  
  50.             $scope.employees = data;  
  51.         }).error(function(data) {  
  52.             $scope.error = "An Error has occured while Delete employee! " + data;  
  53.         });  
  54.     }  
  55.     $scope.cancel = function() {  
  56.         $scope.updateShow = false;  
  57.         $scope.addShow = true;  
  58.         $scope.newemployee = '';  
  59.     }  
  60. }   

Code decription 

  1. var app = angular.module('myApp', []);  
  2. app.controller('employeeController', ['$scope''$http', employeeController]);   

Here, I have added one controller name in Angular JS file named employeeController. 

  1. function employeeController($scope, $http) {  
  2.     $scope.loading = true;  
  3.     $scope.updateShow = false;  
  4.     $scope.addShow = true;   

Here, I added Angularjs Controller

  1. function employeeController($scope, $http)   

Now, declare the variables. 

  1. $scope.loading = true;  
  2. $scope.updateShow = false;  
  3. $scope.addShow = true;   

To get all employee through API controller, write the code shown below. 

  1. $http.get('/api/EmployeeAPI/').success(function(data) {  
  2.     $scope.employees = data;  
  3. }).error(function() {  
  4.     $scope.error = "An Error has occured while loading posts!";  
  5. });   

The default route template mentioned is WebApiConfig.cs file. 

  1. $http.get('/api/EmployeeAPI/')   

To Insert an employee through API controller, write the code, as shown below. 

  1. $scope.add = function() {  
  2.     $scope.loading = true;  
  3.     $http.post('/api/EmployeeAPI/'this.newemployee).success(function(data) {  
  4.         $scope.employees = data;  
  5.         $scope.updateShow = false;  
  6.         $scope.addShow = true;  
  7.         $scope.newemployee = '';  
  8.     }).error(function(data) {  
  9.         $scope.error = "An Error has occured while Saving employee! " + data;  
  10.     });  
  11. }   

To update an employee through API Controller. Write the code, as shown below.

  1. $scope.edit = function () {  
  2.   
  3.         var Id = this.employee.Id;  
  4.   
  5.         $http.get('/api/EmployeeAPI/' + Id).success(function (data) {  
  6.   
  7.             $scope.newemployee = data;  
  8.   
  9.             $scope.updateShow = true;  
  10.   
  11.             $scope.addShow = false;  
  12.   
  13.         }).error(function () {  
  14.   
  15.             $scope.error = "An Error has occured while loading posts!";  
  16.   
  17.         });  
  18.   
  19.     }  
  20.   
  21.    
  22.   
  23.     $scope.update = function () {  
  24.   
  25.         $scope.loading = true;  
  26.   
  27.         console.log(this.newemployee);  
  28.   
  29.         $http.put('/api/EmployeeAPI/'this.newemployee).success(function (data) {  
  30.   
  31.             $scope.employees = data;  
  32.   
  33.             $scope.updateShow = false;  
  34.   
  35.             $scope.addShow = true;  
  36.   
  37.             $scope.newemployee = '';  
  38.   
  39.         }).error(function (data) {  
  40.   
  41.             $scope.error = "An Error has occured while Updating employee! " + data;  
  42.   
  43.         });  
  44.   
  45.     }  

To delete an employee through API Controller, write the code, as shown below. 

  1. $scope.delete = function() {  
  2.     var Id = this.employee.Id;  
  3.     $scope.loading = true;  
  4.     $http.delete('/api/EmployeeAPI/' + Id).success(function(data) {  
  5.         $scope.employees = data;  
  6.     }).error(function(data) {  
  7.         $scope.error = "An Error has occured while Delete employee! " + data;  
  8.     });  
  9. }   

To cancel an employee, write the code, as shown below. 

  1. $scope.cancel = function () {  
  2.         $scope.updateShow = false;  
  3.         $scope.addShow = true;  
  4.         $scope.newemployee = '';  
  5.     }   

Asp.net

Step 10

Check For “WebApiConfig.cs” for API Controller and  “RouteConfig.cs” for normal Controller class file .

Code Ref. of WebApiConfig.cs 

  1. public static void Register(HttpConfiguration config)  
  2.         {  
  3.             config.Routes.MapHttpRoute(  
  4.                 name: "DefaultApi",  
  5.                 routeTemplate: "api/{controller}/{id}",  
  6.                 defaults: new { id = RouteParameter.Optional }  
  7.             );  
  8.         }   

This class file will configure “EmployeeAPIController.cs” API Controller class file.

Code Ref. of RouteConfig.cs 

  1. public static void RegisterRoutes(RouteCollection routes)  
  2.         {  
  3.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.   
  5.             routes.MapRoute(  
  6.                 name: "Default",  
  7.                 url: "{controller}/{action}/{id}",  
  8.                 defaults: new { controller = "Test", action = "Index", id = UrlParameter.Optional }  
  9.             );  
  10.         }   

This class file will configure TestController.cs normal controller class file.

  Asp.net

Asp.net

Step 11

Create a View named Index.cshtml.

Code Ref 

  1. @Scripts.Render("~/js")  
  2. @Styles.Render("~/css")  
  3.   
  4. <html ng-app="myApp">  
  5. <head><title>Satyaprakash - MVC AngularJs With WebApi</title></head>  
  6. <body>  
  7.     <div ng-controller="employeeController" class="container">          
  8.         <div class="row">  
  9.             <div class="col-md-12">  
  10.                 <h3 class="header">EMPLOYEE CRUD USING ANGULARJS AND WEBAPI</h3>  
  11.             </div>  
  12.         </div>  
  13.         <div class="row">              
  14.             <div class="col-md-12">  
  15.                 <strong class="error">{{error}}</strong>  
  16.                 <form name="addemployee" style="width: 600px; margin: 0px auto;">  
  17.                     <div class="form-group">  
  18.                         <label for="cname" class="col-sm-2 control-label">Name:</label>  
  19.                         <div class="col-sm-10 space">  
  20.                             <input type="text" class="form-control" id="cname" placeholder="please enter your name" ng-model="newemployee.Name" required />  
  21.                         </div>  
  22.                     </div>  
  23.                     <div class="form-group">  
  24.                         <label for="address" class="col-sm-2 control-label">Address:</label>  
  25.                         <div class="col-sm-10 space">                              
  26.                             <textarea class="form-control" id="address" placeholder="please enter your address" ng-model="newemployee.Address" required></textarea>  
  27.                         </div>  
  28.                     </div>  
  29.                     <div class="form-group">  
  30.                         <label for="country" class="col-sm-2 control-label">Domicile:</label>  
  31.                         <div class="col-sm-10 space">  
  32.                             <input type="text" class="form-control" id="country" placeholder="please enter your native" ng-model="newemployee.Country" required />  
  33.                         </div>  
  34.                     </div>  
  35.                     <div class="form-group">  
  36.                         <label for="city" class="col-sm-2 control-label">Town:</label>  
  37.                         <div class="col-sm-10 space">  
  38.                             <input type="text" class="form-control" id="city" placeholder="please enter your town" ng-model="newemployee.City" required />  
  39.                         </div>  
  40.                     </div>  
  41.                     <div class="form-group">  
  42.                         <label for="mobile" class="col-sm-2 control-label">Contact:</label>  
  43.                         <div class="col-sm-10 space">  
  44.                             <input type="text" class="form-control" id="mobile" placeholder="please enter your Contact no." ng-model="newemployee.Mobile" required />  
  45.                         </div>  
  46.                     </div>  
  47.                     <br />  
  48.                     <div class="form-group space">  
  49.                         <div class="col-sm-offset-2 col-sm-10">  
  50.                             <input type="submit" value="Insert" ng-click="add()" ng-show="addShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />  
  51.                             <input type="submit" value="Update" ng-click="update()" ng-show="updateShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />  
  52.                             <input type="button" value="Reset" ng-click="cancel()" class="btn btn-primary" />  
  53.                         </div>  
  54.                     </div>  
  55.                     <br />  
  56.                 </form>  
  57.             </div>  
  58.         </div>  
  59.         <div class="row">  
  60.             <div class="col-md-12">  
  61.                 <div class="table-responsive">  
  62.                     <table class="table table-bordered table-hover" style="width: 800px; margin-left: 170px;">  
  63.                         <tr>  
  64.                             <th>Name</th>  
  65.                             <th>Address</th>  
  66.                             <th>Domicile</th>  
  67.                             <th>Town</th>  
  68.                             <th>Contact</th>  
  69.                             <th>Actions</th>  
  70.                         </tr>  
  71.                         <tr ng-repeat="employee in employees">  
  72.                             <td>  
  73.                                 <p>{{ employee.Name }}</p>  
  74.                             </td>  
  75.                             <td>  
  76.                                 <p>{{ employee.Address }}</p>  
  77.                             </td>  
  78.                             <td>  
  79.                                 <p>{{ employee.Country }}</p>  
  80.                             </td>  
  81.                             <td>  
  82.                                 <p>{{ employee.City }}</p>  
  83.                             </td>  
  84.                             <td>  
  85.                                 <p>{{ employee.Mobile }}</p>  
  86.                             </td>  
  87.                             <td>  
  88.                                 <p><a ng-click="edit()" href="javascript:void(0);">Edit</a> | <a ng-click="delete()" href="javascript:void(0);">Delete</a></p>  
  89.                             </td>  
  90.                         </tr>  
  91.                     </table>  
  92.                 </div>  
  93.             </div>  
  94.         </div>          
  95.     </div>  
  96.     <footer>  
  97.         <p style="background-color: Yellow;text-align:center ; color:blue"> @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  98.     </footer>  
  99. </body>  
  100. </html>   

Code description

Here, I have added two reference files of CSS and JS file inside CSS and JS folder. 

  1. @Scripts.Render("~/js")  
  2. @Styles.Render("~/css")   

To access the functionalities of “App.js” file, add one Directive with the file name.

  1. <html ng-app="myApp">   

To access the functionalities of “App.js” controller file, add one Directive with the file name.

  1. <div ng-controller="employeeController" class="container">   

Here, I added some bootstral.css class file. 

  1. <div class="row">  
  2.             <div class="col-md-12">  
  3.                 <h3 class="header">EMPLOYEE CRUD USING ANGULARJS AND WEBAPI</h3>  
  4.             </div>  
  5. </div>   

Inside a form, I added some controls like textboxes and buttons with some properties. 

  1. <form name="addemployee" style="width: 600px; margin: 0px auto;">  
  2.                     <div class="form-group">  
  3.                         <label for="cname" class="col-sm-2 control-label">Name:</label>  
  4.                         <div class="col-sm-10 space">  
  5.                             <input type="text" class="form-control" id="cname" placeholder="please enter your name" ng-model="newemployee.Name" required />  
  6.                         </div>  
  7.                     </div>  
  8.                     <div class="form-group">  
  9.                         <label for="address" class="col-sm-2 control-label">Address:</label>  
  10.                         <div class="col-sm-10 space">                              
  11.                             <textarea class="form-control" id="address" placeholder="please enter your address" ng-model="newemployee.Address" required></textarea>  
  12.                         </div>  
  13.                     </div>  
  14.                     <div class="form-group">  
  15.                         <label for="country" class="col-sm-2 control-label">Domicile:</label>  
  16.                         <div class="col-sm-10 space">  
  17.                             <input type="text" class="form-control" id="country" placeholder="please enter your native" ng-model="newemployee.Country" required />  
  18.                         </div>  
  19.                     </div>  
  20.                     <div class="form-group">  
  21.                         <label for="city" class="col-sm-2 control-label">Town:</label>  
  22.                         <div class="col-sm-10 space">  
  23.                             <input type="text" class="form-control" id="city" placeholder="please enter your town" ng-model="newemployee.City" required />  
  24.                         </div>  
  25.                     </div>  
  26.                     <div class="form-group">  
  27.                         <label for="mobile" class="col-sm-2 control-label">Contact:</label>  
  28.                         <div class="col-sm-10 space">  
  29.                             <input type="text" class="form-control" id="mobile" placeholder="please enter your Contact no." ng-model="newemployee.Mobile" required />  
  30.                         </div>  
  31.                     </div>  
  32.                     <br />  
  33.                     <div class="form-group space">  
  34.                         <div class="col-sm-offset-2 col-sm-10">  
  35.                             <input type="submit" value="Insert" ng-click="add()" ng-show="addShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />  
  36.                             <input type="submit" value="Update" ng-click="update()" ng-show="updateShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />  
  37.                             <input type="button" value="Reset" ng-click="cancel()" class="btn btn-primary" />  
  38.                         </div>  
  39.                     </div>  
  40.                     <br />  
  41.                 </form>   

Here, I added one error functionality, which is defined in “App.js” file, if during data load time.

  1. <strong class="error">{{error}}</strong>   

Here, I added 3 button controls with very nice app.js and bootstrap.css properties. 

  1. <input type="submit" value="Insert" ng-click="add()" ng-show="addShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />  
  2.                             <input type="submit" value="Update" ng-click="update()" ng-show="updateShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />  
  3.                             <input type="button" value="Reset" ng-click="cancel()" class="btn btn-primary" />   

Here, “ng-click” attributes are mentioned to access create, update, delete, cancel/reset functionalities from “App.Js” file.

Here, “ng-show” , “ng-disabled” attributes are mentioned, which are based on the valid data which needs to be checked, if these are in the input controls or not.

Here, class “btn btn-primary” bootstrap class is used for design layout in button controls.

The button control will be changed, which is based on new data entry and updates an existing employee's details. 

  1. <div class="row">  
  2.             <div class="col-md-12">  
  3.                 <div class="table-responsive">  
  4.                     <table class="table table-bordered table-hover" style="width: 800px; margin-left: 170px;">  
  5.                         <tr>  
  6.                             <th>Name</th>  
  7.                             <th>Address</th>  
  8.                             <th>Domicile</th>  
  9.                             <th>Town</th>  
  10.                             <th>Contact</th>  
  11.                             <th>Actions</th>  
  12.                         </tr>  
  13.                         <tr ng-repeat="employee in employees">  
  14.                             <td>  
  15.                                 <p>{{ employee.Name }}</p>  
  16.                             </td>  
  17.                             <td>  
  18.                                 <p>{{ employee.Address }}</p>  
  19.                             </td>  
  20.                             <td>  
  21.                                 <p>{{ employee.Country }}</p>  
  22.                             </td>  
  23.                             <td>  
  24.                                 <p>{{ employee.City }}</p>  
  25.                             </td>  
  26.                             <td>  
  27.                                 <p>{{ employee.Mobile }}</p>  
  28.                             </td>  
  29.                             <td>  
  30.                                 <p><a ng-click="edit()" href="javascript:void(0);">Edit</a> | <a ng-click="delete()" href="javascript:void(0);">Delete</a></p>  
  31.                             </td>  
  32.                         </tr>  
  33.                     </table>  
  34.                 </div>  
  35.             </div>  
  36.         </div>          
  37.     </div>   

Here, I have added table style, using bootsrap.css file. 

  1. <div class="table-responsive">  
  2.                     <table class="table table-bordered table-hover" style="width: 800px; margin-left: 170px;">   

Here, I added one table with all the column values as well as with edit and delete link functionalities. 

  1. <tr>  
  2.                             <th>Name</th>  
  3.                             <th>Address</th>  
  4.                             <th>Domicile</th>  
  5.                             <th>Town</th>  
  6.                             <th>Contact</th>  
  7.                             <th>Actions</th>  
  8.                         </tr>  
  9.                         <tr ng-repeat="employee in employees">  
  10.                             <td>  
  11.                                 <p>{{ employee.Name }}</p>  
  12.                             </td>  
  13.                             <td>  
  14.                                 <p>{{ employee.Address }}</p>  
  15.                             </td>  
  16.                             <td>  
  17.                                 <p>{{ employee.Country }}</p>  
  18.                             </td>  
  19.                             <td>  
  20.                                 <p>{{ employee.City }}</p>  
  21.                             </td>  
  22.                             <td>  
  23.                                 <p>{{ employee.Mobile }}</p>  
  24.                             </td>  
  25.                             <td>   

The model class file with the entities are given below in Model.edmx. 

  1. <td>  
  2.                                 <p>{{ employee.Name }}</p>  
  3.                             </td>  
  4.                             <td>  
  5.                                 <p>{{ employee.Address }}</p>  
  6.                             </td>  
  7.                             <td>  
  8.                                 <p>{{ employee.Country }}</p>  
  9.                             </td>  
  10.                             <td>  
  11.                                 <p>{{ employee.City }}</p>  
  12.                             </td>  
  13.                             <td>  
  14.                                 <p>{{ employee.Mobile }}</p>  
  15.                             </td>  
  16. The link button associate with “app.js” edit and delete functionalities using “ng-click” directives.  
  17.                             <td>  
  18.                                 <p><a ng-click="edit()" href="javascript:void(0);">Edit</a> | <a ng-click="delete()" href="javascript:void(0);">Delete</a></p>  
  19.                             </td>   

Here, I have added footer section to show current date and time. 

  1. <footer>  
  2.         <p style="background-color: Yellow;text-align:center ; color:blue"> @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  3.     </footer>   

Step 12

Here, I have added some CSS and JS file reference  in “BundleConfig.cs” file.

Code Ref 

  1. public static void RegisterBundles(BundleCollection bundles)  
  2.         {  
  3.             bundles.Add(new ScriptBundle("~/js").Include(  
  4.                "~/js/angular.js",  
  5.                "~/js/app.js"));  
  6.   
  7.             bundles.Add(new StyleBundle("~/css").Include(  
  8.                 "~/css/bootstrap.css"));  
  9.         }   

Asp.net 

Application OutPut

The URL of this AngularJS and WebAPI MVC Application is given below.

http://localhost:52159/Test/index

Here, test is the Controller name and Index is the controller action method name.

Here, I will insert one record, as shown below in the table.

Asp.net 

When I click the edit link, the button changed to Update and I changed Bangalore to Bangalore1.

Asp.net

Also, the data is updated from Bangalore to Bangalore1.

Asp.net

No entry is there in the respective text boxes. Thus, Insert button Is disabled.

Asp.net 

After I put data in all textboxes the Insert Button Is Enabled.

Asp.net
 

After clicking, Reset button needs to be used. All the entries in textboxes are removed and again Insert button is disabled.

Asp.net

When we click delete link button, the data is deleted and table now has empty records.

Asp.net

The footer part of this page now shows date, time and some copyright information to make it look professional.

Asp.net

Summary

  1. What is AngularJS?
  2. Create WebAPI Controller and normal Controller.
  3. AngularJs and WebAPI relation in an App.js file.
  4. Bootstrap and AngularJS references used in View Cshtml file.

Next Recommended Readings