Introduction

In this article, I am going to explain how to perform CRUD operations in ASP.NET MVC using AngularJS and WEB API 2 With Stored Procedure.

MVC AngularJS CRUD Operation Using WEB API 2 With Stored Procedure

So, you should follow the below steps to create a web application.

Step 1

New, create a database table and you can follow this query.

  1. CREATE TABLE [dbo].[Employee] (
  2. [Id] INT IDENTITY (1, 1) NOT NULL,
  3. [Name] NVARCHAR (50) NOT NULL,
  4. [Address] NVARCHAR (50) NOT NULL,
  5. [Country] NVARCHAR (50) NOT NULL,
  6. [City] NVARCHAR (50) NOT NULL,
  7. [Mobile] NVARCHAR (10) NOT NULL,
  8. PRIMARY KEY CLUSTERED ([Id] ASC)
  9. );

Step 2

Create a Stored Procedure.

  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' )
  12. BEGIN
  13. INSERT INTO Employee
  14. VALUES ( @name, @address, @country, @city, @mobile )
  15. END
  16. IF ( @type = 'Upd' )
  17. BEGIN
  18. UPDATE Employee
  19. SET Name = @name ,
  20. [Address] = @address ,
  21. Country = @country ,
  22. City = @city ,
  23. Mobile = @mobile
  24. WHERE Id = @id
  25. END
  26. IF ( @type = 'Del' )
  27. BEGIN
  28. DELETE FROM Employee
  29. WHERE Id = @id
  30. END
  31. IF ( @type = 'GetById' )
  32. BEGIN
  33. SELECT *
  34. FROM Employee
  35. WHERE Id = @id
  36. END
  37. SELECT *
  38. FROM Employee
  39. END

Step 3

Open Visual Studio and click File > New > Project.

Step 4

Click on Web from the left-side panel and select ASP.NET MVC4 Web Application. Give it a name and click OK.

Step 5

Select "INTERNET APPLICATION".

Step 6

Right-click on Controller and click Add >> Controller.

Step 7

Give a name to your controller and select Empty API Controller.

Step 8

Right-click on App_Data folder and select Add > New Item.

Step 9

Select SQL Server database and give it a name and Click OK.

Step 10

Right-click on Models and click Add > New Item.

Step 11

Select ADO.NET Entity Data Model.

Step 12

Select "Generate from database" and click "Next".

Step 13

Choose the appropriate database connection and click "Next".

Step 14

Select the created table and created Stored Procedure.

Entity Data Model



Step 15

Write the following code in Model.
  1. namespace AngularJs_With_Web_API.Models
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. public partial class Employee
  6. {
  7. public int Id { get; set; }
  8. public string Name { get; set; }
  9. public string Address { get; set; }
  10. public string Country { get; set; }
  11. public string City { get; set; }
  12. public string Mobile { get; set; }
  13. }
  14. }

Step 16

Now, write the following code in BundleConfig.cs file.

  1. using System.Web;
  2. using System.Web.Optimization;
  3. namespace AngularJs_With_Web_API
  4. {
  5. public class BundleConfig
  6. {
  7. // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
  8. public static void RegisterBundles(BundleCollection bundles)
  9. {
  10. bundles.Add(new ScriptBundle("~/js").Include(
  11. "~/js/angular.js",
  12. "~/js/app.js"));
  13. bundles.Add(new StyleBundle("~/css").Include(
  14. "~/css/bootstrap.css"));
  15. }
  16. }
  17. }

Step 17

Now, if talking about View, then write the following code in Index.cshtml file.

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

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

Step 19

Add the following code to Controller file.

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

Step 20

Write the following code in WebApiConfig.cs file.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web.Http;
  5. namespace AngularJs_With_Web_API
  6. {
  7. public static class WebApiConfig
  8. {
  9. public static void Register(HttpConfiguration config)
  10. {
  11. config.Routes.MapHttpRoute(
  12. name: "DefaultApi",
  13. routeTemplate: "api/{controller}/{id}",
  14. defaults: new { id = RouteParameter.Optional }
  15. );
  16. // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable return type.
  17. // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
  18. // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
  19. //config.EnableQuerySupport();
  20. }
  21. }
  22. }

Step 21

Write the following code in API Controller.

  1. using AngularJs_With_Web_API.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 AngularJs_With_Web_API.Controllers
  11. {
  12. public class EmployeeAPIController : ApiController
  13. {
  14. // Get All The Employee
  15. [HttpGet]
  16. public List Get()
  17. {
  18. List emplist = new List();
  19. using (dbEntities db = new dbEntities())
  20. {
  21. var results = db.sp_InsUpdDelEmployee(0, "", "", "", "", "", "Get").ToList();
  22. foreach (var result in results)
  23. {
  24. var employee = new Employee()
  25. {
  26. Id = result.Id,
  27. Name = result.Name,
  28. Address = result.Address,
  29. Country = result.Country,
  30. City = result.City,
  31. Mobile = result.Mobile
  32. };
  33. emplist.Add(employee);
  34. }
  35. return emplist;
  36. }
  37. }
  38. // Get Employee By Id
  39. public Employee Get(int id)
  40. {
  41. using (dbEntities db = new dbEntities())
  42. {
  43. Employee employee = db.Employees.Find(id);
  44. if (employee == null)
  45. {
  46. throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
  47. }
  48. return employee;
  49. }
  50. }
  51. // Insert Employee
  52. public HttpResponseMessage Post(Employee employee)
  53. {
  54. if (ModelState.IsValid)
  55. {
  56. using (dbEntities db = new dbEntities())
  57. {
  58. var emplist = db.sp_InsUpdDelEmployee(0, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Ins").ToList();
  59. HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, emplist);
  60. return response;
  61. }
  62. }
  63. else
  64. {
  65. return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  66. }
  67. }
  68. // Update Employee
  69. public HttpResponseMessage Put(Employee employee)
  70. {
  71. List emplist = new List();
  72. if (!ModelState.IsValid)
  73. {
  74. return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  75. }
  76. using (dbEntities db = new dbEntities())
  77. {
  78. try
  79. {
  80. emplist = db.sp_InsUpdDelEmployee(employee.Id, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Upd").ToList();
  81. }
  82. catch (DbUpdateConcurrencyException ex)
  83. {
  84. return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
  85. }
  86. }
  87. return Request.CreateResponse(HttpStatusCode.OK, emplist);
  88. }
  89. // Delete employee By Id
  90. public HttpResponseMessage Delete(int id)
  91. {
  92. using (dbEntities db = new dbEntities())
  93. {
  94. List emplist = new List();
  95. var results = db.sp_InsUpdDelEmployee(id, "", "", "", "", "", "GetById").ToList();
  96. if (results.Count == 0)
  97. {
  98. return Request.CreateResponse(HttpStatusCode.NotFound);
  99. }
  100. try
  101. {
  102. emplist = db.sp_InsUpdDelEmployee(id, "", "", "", "", "", "Del").ToList();
  103. }
  104. catch (DbUpdateConcurrencyException ex)
  105. {
  106. return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
  107. }
  108. return Request.CreateResponse(HttpStatusCode.OK, emplist);
  109. }
  110. }
  111. // Prevent Memory Leak
  112. protected override void Dispose(bool disposing)
  113. {
  114. using (dbEntities db = new dbEntities())
  115. db.Dispose();
  116. base.Dispose(disposing);
  117. }
  118. }
  119. }

Summary

In this write-up, I clearly explained how to perform CURD operations in ASP.NET MVC with AngulerJS using Web API and also explain how to use Stored Procedure. I hope this article will be helpful to the beginners.