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].
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.
From the New ASP.NET Project Window. Choose Web API project and click OK.
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.
- using System;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
-
- namespace CRUDwithAngularJSAndWebAPI.Models
- {
- [Table("Employees")]
- public class EmployeeModel
- {
- [Key]
- public int EmployeeID { get; set; }
-
- [Required(ErrorMessage ="First Name Required")]
- [StringLength(maximumLength:20, MinimumLength =3, ErrorMessage ="Name should be between 3 to 20 characters")]
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Address { get; set; }
- public float Salary { get; set; }
- public DateTime DOB { get; set; }
-
- }
- }
Following is the database access context class, where I have defined the database connection.
- using System.Data.Entity;
- namespace CRUDwithAngularJSAndWebAPI.Models
- {
- public class DataAccessContext : DbContext
- {
- public DataAccessContext() : base("testconnection")
- {
- }
-
- public DbSet<EmployeeModel> Employees { get; set; }
- }
- }
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".
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.
- using CRUDwithAngularJSAndWebAPI.Models;
- using CRUDwithAngularJSAndWebAPI.ViewModel;
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
-
-
- namespace CRUDwithAngularJSAndWebAPI.Controllers
- {
-
- public class EmployeeController : ApiController
- {
-
- DataAccessContext context = new DataAccessContext();
-
-
- [HttpGet]
- public IEnumerable<EmployeeViewModel> GetAllEmployee()
- {
-
- var data = context.Employees.ToList().OrderBy(x=>x.FirstName);
- var result = data.Select(x => new EmployeeViewModel()
- {
- EmployeeID = x.EmployeeID,
- FirstName = x.FirstName,
- LastName = x.LastName,
- Address = x.Address,
- Salary = x.Salary,
- DOB = x.DOB
- });
- return result.ToList();
- }
-
-
-
- [HttpGet]
- public EmployeeViewModel GetEmployee(int Id)
- {
- var data = context.Employees.Where(x => x.EmployeeID == Id).FirstOrDefault();
- if (data != null)
- {
- EmployeeViewModel employee = new EmployeeViewModel();
- employee.EmployeeID = data.EmployeeID;
- employee.FirstName = data.FirstName;
- employee.LastName = data.LastName;
- employee.Address = data.Address;
- employee.Salary = data.Salary;
- employee.DOB = data.DOB;
-
- return employee;
- }
- else
- {
- throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
- }
- }
-
-
-
- [HttpPost]
- public HttpResponseMessage AddEmployee(EmployeeViewModel model)
- {
- try
- {
- if (ModelState.IsValid)
- {
- EmployeeModel emp = new EmployeeModel();
- emp.FirstName = model.FirstName;
- emp.LastName = model.LastName;
- emp.Address = model.Address;
- emp.Salary = model.Salary;
- emp.DOB = Convert.ToDateTime(model.DOB.ToString("yyyy-MM-dd HH:mm:ss.fff"));
-
- context.Employees.Add(emp);
- var result = context.SaveChanges();
- if (result > 0)
- {
- return Request.CreateResponse(HttpStatusCode.Created, "Submitted Successfully");
- }
- else
- {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something wrong !");
- }
- }
- else
- {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something wrong !");
- }
- }
- catch (Exception ex)
- {
-
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something wrong !", ex);
- }
- }
-
-
-
- [HttpPut]
- public HttpResponseMessage UpdateEmployee(EmployeeViewModel model)
- {
- try
- {
- if (ModelState.IsValid)
- {
- EmployeeModel emp = new EmployeeModel();
- emp.EmployeeID = model.EmployeeID;
- emp.FirstName = model.FirstName;
- emp.LastName = model.LastName;
- emp.Address = model.Address;
- emp.Salary = model.Salary;
- emp.DOB = Convert.ToDateTime(model.DOB.ToString("yyyy-MM-dd HH:mm:ss.fff"));
-
- context.Entry(emp).State = System.Data.Entity.EntityState.Modified;
- var result = context.SaveChanges();
- if (result > 0)
- {
- return Request.CreateResponse(HttpStatusCode.OK, "Updated Successfully");
- }
- else
- {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Something wrong !");
- }
- }
- else
- {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something wrong !");
- }
- }
- catch (Exception ex)
- {
-
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something wrong !", ex);
- }
- }
-
-
-
- [HttpDelete]
- public HttpResponseMessage DeleteEmployee(int Id)
- {
- EmployeeModel emp = new EmployeeModel();
- emp = context.Employees.Find(Id);
- if (emp != null)
- {
- context.Employees.Remove(emp);
- context.SaveChanges();
- return Request.CreateResponse(HttpStatusCode.OK, emp);
- }
- else
- {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Something wrong !");
- }
- }
- }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace CRUDwithAngularJSAndWebAPI.ViewModel
- {
- public class EmployeeViewModel
- {
- public int EmployeeID { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Address { get; set; }
- public float Salary { get; set; }
- public DateTime DOB { get; set; }
-
-
- public int DepartmentID { get; set; }
- public string DepartmentName { get; set; }
- }
- }
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.
- <connectionStrings>
- <add name="testconnection" connectionString="Data Source=my-computer; database = DemoTest; user id = mukesh; password =adminadmin;" providerName="System.Data.SqlClient" />
- </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.