The following are the highlights of this article:

  1. Create a Database. (SchoolManagement).
  2. Create a Table (Student).
  3. Create a MVC 4 application.
  4. Add a WEB API.
  5. Use AngularJs to consume WEB API.
  6. Perform the CRUD (Create, Read, Update & Delete) operations using Angular with WEB API.

Angular

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. AngularJS is a JavaScript framework. Its goal is to augment browser-based applications with Model–View–Controller (MVC) capability, in an effort to make both development and testing easier.

This article shows how to manage Student Data.

The following is my Data Table.

design view
Image 1

The following is the script for my Data Table:
  1. CREATE TABLE [dbo].[Student](
  2. [StudentID] [int] IDENTITY(1,1) NOT NULL,
  3. [Name] [varchar](50) NULL,
  4. [Email] [varchar](500) NULL,
  5. [Class] [varchar](50) NULL,
  6. [EnrollYear] [varchar](50) NULL,
  7. [City] [varchar](50) NULL,
  8. [Country] [varchar](50) NULL,
  9. CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED
  10. (
  11. [StudentID] ASC
  12. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  13. ) ON [PRIMARY]
  14. GO
  15. SET ANSI_PADDING OFF
  16. GO
Now open Visual Studio and create a project.

mvc web application
Image 2

Select ASP.NET MVC 4 Web Application then click OK.

internet application
Image 3

Now we will add the database. So right-click on the Model then select Add -> ADO.NET Entity Data Model.

entity data model
Image 4

Provide it a name.

item name
Image 5

Enter your database connection properties.

generate from database
Image 6

servername
Image 7

data connection
Image 8

select table name
Image 9

properties
Image 10

Now it is time to add a new Web API controller. So right-click on the Controller then select Add -> Controller.

add controller
Image 11

Here select API controller with read/write actions, using Entity Framework in Template option, select Model class and select Data Context Class ->ADD.

controller name
Image 12

It will add a StudentAPI controller with the following automatically generated code with methods for GET, PUT, POST and DELETE.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.Entity;
  5. using System.Data.Entity.Infrastructure;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Web;
  10. using System.Web.Http;
  11. using MVC4_WEBApi_Angular_CRUD.Models;
  12. namespace MVC4_WEBApi_Angular_CRUD.Controllers
  13. {
  14. public class StudentsAPIController : ApiController
  15. {
  16. private SchoolManagementEntities db = new SchoolManagementEntities();
  17. // GET api/StudentsAPI
  18. public IEnumerable<Student> GetStudents()
  19. {
  20. return db.Student.AsEnumerable();
  21. }
  22. // GET api/StudentsAPI/5
  23. public Student GetStudent(int id)
  24. {
  25. Student student = db.Student.Find(id);
  26. if (student == null)
  27. {
  28. throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
  29. }
  30. return student;
  31. }
  32. // PUT api/StudentsAPI/5
  33. public HttpResponseMessage PutStudent(int id, Student student)
  34. {
  35. if (ModelState.IsValid && id == student.StudentID)
  36. {
  37. db.Entry(student).State = EntityState.Modified;
  38. try
  39. {
  40. db.SaveChanges();
  41. }
  42. catch (DbUpdateConcurrencyException)
  43. {
  44. return Request.CreateResponse(HttpStatusCode.NotFound);
  45. }
  46. return Request.CreateResponse(HttpStatusCode.OK);
  47. }
  48. else
  49. {
  50. return Request.CreateResponse(HttpStatusCode.BadRequest);
  51. }
  52. }
  53. // POST api/StudentsAPI
  54. public HttpResponseMessage PostStudent(Student student)
  55. {
  56. if (ModelState.IsValid)
  57. {
  58. db.Student.Add(student);
  59. db.SaveChanges();
  60. HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, student);
  61. response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = student.StudentID }));
  62. return response;
  63. }
  64. else
  65. {
  66. return Request.CreateResponse(HttpStatusCode.BadRequest);
  67. }
  68. }
  69. // DELETE api/StudentsAPI/5
  70. public HttpResponseMessage DeleteStudent(int id)
  71. {
  72. Student student = db.Student.Find(id);
  73. if (student == null)
  74. {
  75. return Request.CreateResponse(HttpStatusCode.NotFound);
  76. }
  77. db.Student.Remove(student);
  78. try
  79. {
  80. db.SaveChanges();
  81. }
  82. catch (DbUpdateConcurrencyException)
  83. {
  84. return Request.CreateResponse(HttpStatusCode.NotFound);
  85. }
  86. return Request.CreateResponse(HttpStatusCode.OK, student);
  87. }
  88. protected override void Dispose(bool disposing)
  89. {
  90. db.Dispose();
  91. base.Dispose(disposing);
  92. }
  93. }
  94. }
Now we will add a new controller by right-clicking on the Controller Folder then selecting Add -> Controller.

add new controller
Image 13

Select here Empty MVC controller from (Template) Scaffolding options.

type controller name
Image 14

Code
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace MVC4_WEBApi_Angular_CRUD.Controllers
  7. {
  8. public class StudentController : Controller
  9. {
  10. //
  11. // GET: /Student/
  12. public ActionResult Index()
  13. {
  14. return View();
  15. }
  16. }
  17. }
We will add a View after adding an AngularJs reference so right-click on your project name in Solution Explorer then select Manage NuGet Packages option.

manage NUGET Packages
Image 15

install angular JS
Image 16

downloading
Image 17

After adding an AngularJs reference now create a new folder in the Script folder then do something with MyAngularjsScripts and 3 the JavaScript files named as below.
  1. Module.js
  2. Service.js
  3. Controller.js

Module.js

  1. var app;
  2. (function () {
  3. app = angular.module("crudModule", []);
  4. })()
Service.js
  1. app.service('CRUD_OperService', function ($http) {
  2. //Create new record
  3. this.post = function (Student) {
  4. var request = $http({
  5. method: "post",
  6. url: "/api/StudentsAPI",
  7. data: Student
  8. });
  9. return request;
  10. }
  11. //Get Single Records
  12. this.get = function (StudentID) {
  13. return $http.get("/api/StudentsAPI/" + StudentID);
  14. }
  15. //Get All Student
  16. this.getAllStudent = function () {
  17. return $http.get("/api/StudentsAPI");
  18. }
  19. //Update the Record
  20. this.put = function (StudentID, Student) {
  21. var request = $http({
  22. method: "put",
  23. url: "/api/StudentsAPI/" + StudentID,
  24. data: Student
  25. });
  26. return request;
  27. }
  28. //Delete the Record
  29. this.delete = function (StudentID) {
  30. var request = $http({
  31. method: "delete",
  32. url: "/api/StudentsAPI/" + StudentID
  33. });
  34. return request;
  35. }
  36. });
Controller.js
  1. app.controller('CRUD_OperController', function ($scope, CRUD_OperService) {
  2. $scope.OperType = 1;
  3. //1 Mean New Entry
  4. GetAllRecords();
  5. //To Get All Records
  6. function GetAllRecords() {
  7. var promiseGet = CRUD_OperService.getAllStudent();
  8. promiseGet.then(function (pl) { $scope.Students = pl.data },
  9. function (errorPl) {
  10. $log.error('Some Error in Getting Records.', errorPl);
  11. });
  12. }
  13. //To Clear all input controls.
  14. function ClearModels() {
  15. $scope.OperType = 1;
  16. $scope.StudentID = "";
  17. $scope.Name = "";
  18. $scope.Email = "";
  19. $scope.Class = "";
  20. $scope.EnrollYear = "";
  21. $scope.City = "";
  22. $scope.Country = "";
  23. }
  24. //To Create new record and Edit an existing Record.
  25. $scope.save = function () {
  26. var Student = {
  27. Name: $scope.Name,
  28. Email: $scope.Email,
  29. Class: $scope.Class,
  30. EnrollYear: $scope.EnrollYear,
  31. City: $scope.City,
  32. Country: $scope.Country
  33. };
  34. if ($scope.OperType === 1) {
  35. var promisePost = CRUD_OperService.post(Student);
  36. promisePost.then(function (pl) {
  37. $scope.StudentID = pl.data.StudentID;
  38. GetAllRecords();
  39. ClearModels();
  40. }, function (err) {
  41. console.log("Err" + err);
  42. });
  43. } else {
  44. //Edit the record
  45. Student.StudentID = $scope.StudentID;
  46. var promisePut = CRUD_OperService.put($scope.StudentID, Student);
  47. promisePut.then(function (pl) {
  48. $scope.Message = "Student Updated Successfuly";
  49. GetAllRecords();
  50. ClearModels();
  51. }, function (err) {
  52. console.log("Err" + err);
  53. });
  54. }
  55. };
  56. //To Delete Record
  57. $scope.delete = function (Student) {
  58. var promiseDelete = CRUD_OperService.delete(Student.StudentID);
  59. promiseDelete.then(function (pl) {
  60. $scope.Message = "Student Deleted Successfuly";
  61. GetAllRecords();
  62. ClearModels();
  63. }, function (err) {
  64. console.log("Err" + err);
  65. });
  66. }
  67. //To Get Student Detail on the Base of Student ID
  68. $scope.get = function (Student) {
  69. var promiseGetSingle = CRUD_OperService.get(Student.StudentID);
  70. promiseGetSingle.then(function (pl) {
  71. var res = pl.data;
  72. $scope.StudentID = res.StudentID;
  73. $scope.Name = res.Name;
  74. $scope.Email = res.Email;
  75. $scope.Class = res.Class;
  76. $scope.EnrollYear = res.EnrollYear;
  77. $scope.City = res.City;
  78. $scope.Country = res.Country;
  79. $scope.OperType = 0;
  80. },
  81. function (errorPl) {
  82. console.log('Some Error in Getting Details', errorPl);
  83. });
  84. }
  85. //To Clear all Inputs controls value.
  86. $scope.clear = function () {
  87. $scope.OperType = 1;
  88. $scope.StudentID = "";
  89. $scope.Name = "";
  90. $scope.Email = "";
  91. $scope.Class = "";
  92. $scope.EnrollYear = "";
  93. $scope.City = "";
  94. $scope.Country = "";
  95. }
  96. });
Now for StudentControler right-click on the Index method then select Add view.

add view
Image 18

type view name
Image 19

Our Index.cshtml is:
  1. <html data-ng-app="crudModule">
  2. @{
  3. ViewBag.Title = "Manage Student Information using AngularJs, WEB API & MVC4";
  4. }
  5. <body>
  6. <table id="tblContainer" data-ng-controller="CRUD_OperController">
  7. <tr>
  8. <td>
  9. <table style="border: solid 2px Green; padding: 5px;">
  10. <tr style="height: 30px; background-color: skyblue; color: maroon;">
  11. <th></th>
  12. <th>ID</th>
  13. <th>Name</th>
  14. <th>Email</th>
  15. <th>Class</th>
  16. <th>Year</th>
  17. <th>City</th>
  18. <th>Country</th>
  19. <th></th>
  20. <th></th>
  21. </tr>
  22. <tbody data-ng-repeat="stud in Students">
  23. <tr>
  24. <td></td>
  25. <td><span>{{stud.StudentID}}</span></td>
  26. <td><span>{{stud.Name}}</span></td>
  27. <td><span>{{stud.Email}}</span></td>
  28. <td><span>{{stud.Class}}</span></td>
  29. <td><span>{{stud.EnrollYear}}</span></td>
  30. <td><span>{{stud.City}}</span></td>
  31. <td><span>{{stud.Country}}</span></td>
  32. <td>
  33. <input type="button" id="Edit" value="Edit" data-ng-click="get(stud)" /></td>
  34. <td>
  35. <input type="button" id="Delete" value="Delete" data-ng-click="delete(stud)" /></td>
  36. </tr>
  37. </tbody>
  38. </table>
  39. </td>
  40. </tr>
  41. <tr>
  42. <td>
  43. <div style="color: red;">{{Message}}</div>
  44. <table style="border: solid 4px Red; padding: 2px;">
  45. <tr>
  46. <td></td>
  47. <td>
  48. <span>Student ID</span>
  49. </td>
  50. <td>
  51. <input type="text" id="StudentID" readonly="readonly" data-ng-model="StudentID" />
  52. </td>
  53. </tr>
  54. <tr>
  55. <td></td>
  56. <td>
  57. <span>Student Name</span>
  58. </td>
  59. <td>
  60. <input type="text" id="sName" required data-ng-model="Name" />
  61. </td>
  62. </tr>
  63. <tr>
  64. <td></td>
  65. <td>
  66. <span>Email</span>
  67. </td>
  68. <td>
  69. <input type="text" id="sEmail" required data-ng-model="Email" />
  70. </td>
  71. </tr>
  72. <tr>
  73. <td></td>
  74. <td>
  75. <span>Class</span>
  76. </td>
  77. <td>
  78. <input type="text" id="sClass" required data-ng-model="Class" />
  79. </td>
  80. </tr>
  81. <tr>
  82. <td></td>
  83. <td>
  84. <span>Enrollement Year</span>
  85. </td>
  86. <td>
  87. <input type="text" id="sEnrollYear" required data-ng-model="EnrollYear" />
  88. </td>
  89. </tr>
  90. <tr>
  91. <td></td>
  92. <td>
  93. <span>City</span>
  94. </td>
  95. <td>
  96. <input type="text" id="sCity" required data-ng-model="City" />
  97. </td>
  98. </tr>
  99. <tr>
  100. <td></td>
  101. <td>
  102. <span>Country</span>
  103. </td>
  104. <td>
  105. <input type="text" id="sCountry" required data-ng-model="Country" />
  106. </td>
  107. </tr>
  108. <tr>
  109. <td></td>
  110. <td></td>
  111. <td>
  112. <input type="button" id="save" value="Save" data-ng-click="save()" />
  113. <input type="button" id="Clear" value="Clear" data-ng-click="clear()" />
  114. </td>
  115. </tr>
  116. </table>
  117. </td>
  118. </tr>
  119. </table>
  120. </body>
  121. </html>
  122. <script src="~/Scripts/angular.js"></script>
  123. <script src="~/Scripts/angular-route.js"></script>
  124. <script src="~/Scripts/MyAngularjsScripts/Module.js"></script>
  125. <script src="~/Scripts/MyAngularjsScripts/Service.js"></script>
  126. <script src="~/Scripts/MyAngularjsScripts/Controller.js"></script>
Now run the application. You can set a start-up URI from the Route.config file in the APP_START folder like the following:

cs coding
Image 20

Run application: See your all records.

From here you can add a new record, edit any record and delete any record.

ajjularJS
Image 21

web api
Image 22

edit record
Image 23