AngularJS CRUD Operations With Web API - Part One

In this article, I will demonstrate about Angular JS CRUD operations example with Web API. This is part one for this demonstration. In part 2, we will learn about, how to implement Web API with Angular JS client. Web API will be used as a Service to get the data from the database and share the data to AngularJS app. For this demonstration, I have used Code First Approach.

DOWNLOAD CODE


In this example, I will show you, how to make routing in AngularJS and perform CRUD [Create, Read, Update and Delete] Operations. All the operations will be performed with different template pages [HTML page].
crud
Create Asp.Net Application

To create a new Application, open Visual Studio 2015 and Select File -> New -> Project. It will open a New Project Window. Choose Web tab inside Visual C# and then choose ASP.NET Web Application. You can choose your project location and click OK.

Create Asp.Net Application

From the New ASP.NET Project Window. Choose Web API project and click OK.

Web API

Create Model and Context Classes

Following is the employee model, where all the properties have been defined for an employee. I have used Table attribute for the table name.

  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3. using System.ComponentModel.DataAnnotations.Schema;  
  4.   
  5. namespace CRUDwithAngularJSAndWebAPI.Models  
  6. {  
  7.     [Table("Employees")]  
  8.     public class EmployeeModel  
  9.     {  
  10.         [Key]  
  11.         public int EmployeeID { getset; }  
  12.   
  13.         [Required(ErrorMessage ="First Name Required")]  
  14.         [StringLength(maximumLength:20, MinimumLength =3, ErrorMessage ="Name should be between 3 to 20 characters")]  
  15.         public string FirstName { getset; }  
  16.         public string LastName { getset; }  
  17.         public string Address { getset; }  
  18.         public float Salary { getset; }  
  19.         public DateTime DOB { getset; }  
  20.          
  21.     }  
  22. }  
Following is the database access context class, where I have defined the database connection.
  1. using System.Data.Entity;  
  2. namespace CRUDwithAngularJSAndWebAPI.Models  
  3. {  
  4.     public class DataAccessContext : DbContext  
  5.     {  
  6.         public DataAccessContext() : base("testconnection")  
  7.         {  
  8.         }  
  9.   
  10.         public DbSet<EmployeeModel> Employees { get; set; }         
  11.     }  
  12. }  
Create API Controller

We are using Web API to access the data from the database. It will require creating controller to access the data. To create new API controller, right click on Controller folder, choose Add and then select Controller. You need to provide the controller name as "EmployeeController".

EmployeeController

Make the code changes in EmployeeController as following-

Here, I have made the code to Create, Read, Update and Delete. Don't forget to assign the request type with an action method.
  1. using CRUDwithAngularJSAndWebAPI.Models;  
  2. using CRUDwithAngularJSAndWebAPI.ViewModel;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Globalization;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web.Http;  
  10.   
  11.   
  12. namespace CRUDwithAngularJSAndWebAPI.Controllers  
  13. {  
  14.       
  15.     public class EmployeeController : ApiController  
  16.     {  
  17.           
  18.         DataAccessContext context = new DataAccessContext();  
  19.   
  20.         //Get All Employees  
  21.         [HttpGet]          
  22.         public IEnumerable<EmployeeViewModel> GetAllEmployee()  
  23.         {  
  24.   
  25.             var data = context.Employees.ToList().OrderBy(x=>x.FirstName);  
  26.             var result = data.Select(x => new EmployeeViewModel()  
  27.             {  
  28.                 EmployeeID = x.EmployeeID,  
  29.                 FirstName = x.FirstName,  
  30.                 LastName = x.LastName,  
  31.                 Address = x.Address,  
  32.                 Salary = x.Salary,  
  33.                 DOB = x.DOB  
  34.         });  
  35.             return result.ToList();  
  36.         }  
  37.   
  38.   
  39.         //Get the single employee data  
  40.         [HttpGet]  
  41.         public EmployeeViewModel GetEmployee(int Id)  
  42.         {  
  43.             var data = context.Employees.Where(x => x.EmployeeID == Id).FirstOrDefault();  
  44.             if (data != null)  
  45.             {  
  46.                 EmployeeViewModel employee = new EmployeeViewModel();  
  47.                 employee.EmployeeID = data.EmployeeID;  
  48.                 employee.FirstName = data.FirstName;  
  49.                 employee.LastName = data.LastName;  
  50.                 employee.Address = data.Address;  
  51.                 employee.Salary = data.Salary;  
  52.                 employee.DOB = data.DOB;  
  53.   
  54.                 return employee;  
  55.             }  
  56.             else  
  57.             {  
  58.                 throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));  
  59.             }  
  60.         }  
  61.   
  62.         //Add new employee  
  63.   
  64.         [HttpPost]  
  65.         public HttpResponseMessage AddEmployee(EmployeeViewModel model)  
  66.         {  
  67.             try  
  68.             {  
  69.                 if (ModelState.IsValid)  
  70.                 {  
  71.                     EmployeeModel emp = new EmployeeModel();  
  72.                     emp.FirstName = model.FirstName;  
  73.                     emp.LastName = model.LastName;  
  74.                     emp.Address = model.Address;  
  75.                     emp.Salary = model.Salary;  
  76.                     emp.DOB = Convert.ToDateTime(model.DOB.ToString("yyyy-MM-dd HH:mm:ss.fff"));  
  77.                    
  78.                     context.Employees.Add(emp);  
  79.                     var result = context.SaveChanges();  
  80.                     if (result > 0)  
  81.                     {  
  82.                         return Request.CreateResponse(HttpStatusCode.Created, "Submitted Successfully");  
  83.                     }  
  84.                     else  
  85.                     {  
  86.                         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something wrong !");  
  87.                     }  
  88.                 }  
  89.                 else  
  90.                 {  
  91.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something wrong !");  
  92.                 }  
  93.             }  
  94.             catch (Exception ex)  
  95.             {  
  96.   
  97.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something wrong !", ex);  
  98.             }  
  99.         }  
  100.   
  101.         //Update the employee  
  102.   
  103.         [HttpPut]  
  104.         public HttpResponseMessage UpdateEmployee(EmployeeViewModel model)  
  105.         {  
  106.             try  
  107.             {  
  108.                 if (ModelState.IsValid)  
  109.                 {  
  110.                     EmployeeModel emp = new EmployeeModel();  
  111.                     emp.EmployeeID = model.EmployeeID;  
  112.                     emp.FirstName = model.FirstName;  
  113.                     emp.LastName = model.LastName;  
  114.                     emp.Address = model.Address;  
  115.                     emp.Salary = model.Salary;  
  116.                     emp.DOB = Convert.ToDateTime(model.DOB.ToString("yyyy-MM-dd HH:mm:ss.fff"));  
  117.                    
  118.                     context.Entry(emp).State = System.Data.Entity.EntityState.Modified;  
  119.                     var result = context.SaveChanges();  
  120.                     if (result > 0)  
  121.                     {  
  122.                         return Request.CreateResponse(HttpStatusCode.OK, "Updated Successfully");  
  123.                     }  
  124.                     else  
  125.                     {  
  126.                         return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Something wrong !");  
  127.                     }  
  128.                 }  
  129.                 else  
  130.                 {  
  131.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something wrong !");  
  132.                 }  
  133.             }  
  134.             catch (Exception ex)  
  135.             {  
  136.   
  137.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something wrong !", ex);  
  138.             }  
  139.         }  
  140.   
  141.         //Delete the employee  
  142.   
  143.         [HttpDelete]  
  144.         public HttpResponseMessage DeleteEmployee(int Id)  
  145.         {  
  146.             EmployeeModel emp = new EmployeeModel();  
  147.             emp = context.Employees.Find(Id);  
  148.             if (emp != null)  
  149.             {  
  150.                 context.Employees.Remove(emp);  
  151.                 context.SaveChanges();  
  152.                 return Request.CreateResponse(HttpStatusCode.OK, emp);  
  153.             }  
  154.             else  
  155.             {  
  156.                 return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Something wrong !");  
  157.             }  
  158.         }  
  159.     }  
  160. }  
You can see in the code, given above, I used a ViewModel. It is because in future,  if you want to extend the functionality with the relational data and there will not be a long change, View Model is used in order to merge multiple tables’ data.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace CRUDwithAngularJSAndWebAPI.ViewModel  
  7. {  
  8.     public class EmployeeViewModel  
  9.     {  
  10.         public int EmployeeID { get; set; }         
  11.         public string FirstName { get; set; }  
  12.         public string LastName { get; set; }  
  13.         public string Address { get; set; }  
  14.         public float Salary { get; set; }  
  15.         public DateTime DOB { get; set; }  
  16.   
  17.        //Following are the extend properties if you want  
  18.         public int DepartmentID { get; set; }          
  19.         public string DepartmentName { get; set; }  
  20.     }  
  21. }  
Create Connection String

Create a connection string inside the web.config and call it with the database context class. Please make sure to change the user name and password, while running the Application in your system.
  1. <connectionStrings>  
  2.    <add name="testconnection" connectionString="Data Source=my-computer; database = DemoTest; user id = mukesh; password =adminadmin;" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>  
In next part, we will see, how to implement this Web API with AngularJS Application to perform CRUD operations.

Conclusion

Thus, today we learned, how to create a Web API for CRUD operations.

I hope, this post will help you. Please post your feedback, using comments, which helps me to improve myself for the next post. If you have any doubts, please ask  in the comment section and if you like this post, please share it with your friends.

 


Similar Articles