I am a .NET Developer and I’m new in AngularJS. I started using AngularJS in about a week ago and I decided to create a full AngularJS CRUD Operation using ASP.NET MVC. This article will show you how I created a project with CRUD functionality using AngularJS in ASP.Net.

For an overview of AngularJS, you can visit AngularJS introduction from this site https://docs.angularjs.org/guide/introduction.

To start, below are the summary of the steps I have done to fully implement AngularJS in ASP.Net CRUD project.

CRUD Operation using AngularJS in ASP.Net

Create SQL Database

Create CRUD Stored Procedure

Start a New ASP.NET MVC project

Create a separate Class for CRUD functions

Create CRUD Action Result in main controller( HomeController)

Design a View (Front End Design) with AngularJS App

To make this article much easier I copied all the code I have used in every associated class file in the steps above.

Let’s Start:

1. Create SQL Database:

To execute CRUD operation using AngularJS in ASP.NET we need to have data storage. I assume you have already used SQL Database. Create a database and a table. In my case, I created a database named EmployeeDB and a table named EmployeeRecord. Image below.

2. Create CRUD Stored Procedure

If this is your first time using a SQL stored procedure you can refer to my previous article How to create a stored procedure. Below are the Stored Procedures and the associated code I used.

Code:

DeleteEmployee Procedure

USE [EmployeeDB] GO /****** Object: StoredProcedure [dbo].[DeleteEmployee] Script Date: 20/06/2018 9:22:38 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[DeleteEmployee] @ID int AS BEGIN SET NOCOUNT ON; Delete From EmployeeRecord WHERE ID = @ID END

SQL Stored Procedure – InsertEmployee

USE [EmployeeDB] GO /****** Object: StoredProcedure [dbo].[InsertEmployee] Script Date: 20/06/2018 9:22:57 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[InsertEmployee] @Name nvarchar(50), @Email nvarchar(50) AS BEGIN SET NOCOUNT ON; INSERT INTO EmployeeRecord VALUES(@Name, @Email) END

SelectEmployee Procedure

USE [EmployeeDB] GO /****** Object: StoredProcedure [dbo].[SelectEmployee] Script Date: 20/06/2018 9:23:00 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[SelectEmployee] AS BEGIN SET NOCOUNT ON; Select * FROm EmployeeRecord END

UpdateEmployee Procedure

USE [EmployeeDB] GO /****** Object: StoredProcedure [dbo].[UpdateEmployee] Script Date: 20/06/2018 9:23:04 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[UpdateEmployee] @ID int , @Name nvarchar(50), @Email nvarchar(50) AS BEGIN SET NOCOUNT ON; Update EmployeeRecord set Name = @Name , Email = @Email WHERE ID = @ID END

3. Start a New ASP.NET MVC project

Now, that we have already prepared our backend, which is the SQL Database and stored procedures. We can now start creating our project. Open your Visual Studio and create a new ASP.NET Web Application using MVC template. If you have no idea how to start a project you can visit my previous article on how to start in ASP.NET MVC.

4. Create a separate Class for CRUD functions

To organize our code I suggest we create a separate class containing all the connections we need to established connectivity to our SQL Stored Procedures.

But first, let’s create a folder inside our solution explorer by simply right-clicking on the project name and selecting Add > New Folder. See image below

Inside that folder create a Class. Add Class by simply right-clicking your project name and select Add > Class. Below are the folder and class I created.

As you can see from the image above I named my folder as CRUD_function and my class as CRUD. Now, let’s start adding code. Open CRUD.cs and copy the code snippet below. This is where we put all our connection to the SQL Stored procedures.

Note: To view your connection string you can refer to my previous article Manual viewing SQL Connection String.

CRUD.cs – Code:

using AngularJS_CRUD.Models; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; namespace AngularJS_CRUD.Crud_Function { public class CRUD { string connectionString = "Data Source=LAPTOP-JD2CG4N8;Initial Catalog=EmployeeDB;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"; public List<EmployeeModel> GetEmployees() { List<EmployeeModel> list = new List<EmployeeModel>(); using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand("dbo.SelectEmployee", conn); cmd.CommandType = System.Data.CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { list.Add(new EmployeeModel { Name = row["Name"].ToString().Trim(), Email = row["Email"].ToString().Trim(), ID = int.Parse(row["ID"].ToString()) }); } } } } return list; } public string AddEmployee(EmployeeModel empDetails) { string response = ""; using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand("InsertEmployee", conn); cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = empDetails.Name; cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = empDetails.Email; cmd.CommandType = CommandType.StoredProcedure; conn.Open(); cmd.ExecuteNonQuery(); response = "Success"; conn.Close(); } return response; } public string updateEmployee(EmployeeModel empdetails) { string response = ""; using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand("UpdateEmployee", conn); cmd.Parameters.Add("@ID", SqlDbType.Int).Value = empdetails.ID; cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = empdetails.Name; cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = empdetails.Email; cmd.CommandType = CommandType.StoredProcedure; conn.Open(); cmd.ExecuteNonQuery(); response = "Success"; conn.Close(); } return response; } public string deleteEmployee(int id) { string response = ""; using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand("DeleteEmployee", conn); cmd.Parameters.Add("@ID", SqlDbType.Int).Value = id; cmd.CommandType = CommandType.StoredProcedure; conn.Open(); cmd.ExecuteNonQuery(); response = "Success"; conn.Close(); } return response; } } }

5. Create CRUD Action Result in main controller( HomeController)

In this step, we will create an Action Result method in our main controller. If you are using the default MVC template, your default controller is HomeController. Located inside the folder Controller. Open HomeController. Copy the code snippet below.

HomeController.cs – Codes:

using AngularJS_CRUD.Crud_Function; using AngularJS_CRUD.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AngularJS_CRUD.Controllers { public class HomeController : Controller { CRUD service = new CRUD(); public ActionResult Index() { return View(); } [HttpGet] public ActionResult getEmployee() { List<EmployeeModel> list = new List<EmployeeModel>(); list = service.GetEmployees(); string json_data = JsonConvert.SerializeObject(list); return Json(json_data, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult AddEmployee(EmployeeModel empdetails) { string result = service.AddEmployee(empdetails); List<EmployeeModel> list = new List<EmployeeModel>(); list = service.GetEmployees(); string json_data = JsonConvert.SerializeObject(list); return Json(json_data, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult UpdateEmployee(EmployeeModel empdetails) { string result = service.updateEmployee(empdetails); List<EmployeeModel> list = new List<EmployeeModel>(); list = service.GetEmployees(); string json_data = JsonConvert.SerializeObject(list); return Json(json_data, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult DeleteEmployee(int ID) { string result = service.deleteEmployee(ID); List<EmployeeModel> list = new List<EmployeeModel>(); list = service.GetEmployees(); string json_data = JsonConvert.SerializeObject(list); return Json(json_data, JsonRequestBehavior.AllowGet); } } }

6. Design a View (Front End Design) with AngularJS App

After we have fully created all the necessary CRUD functions that we need, let’s start creating our front-end design with the AngularJS framework. Navigate to your default view which is located inside the folder Views > Home > index.cshtml .Open index.cshtml and replace the code with the snippet below.

Project Preview:

Add of employee preview

Index.cshtml – Code:

Note: with AngularJS Script

@using AngularJS_CRUD.Models @model EmployeeModel @{ ViewBag.Title = "Home Page"; } <script src="~/Scripts/Angular.min.js"></script> <div ng-app="HomeApp" ng-controller="HomeController"> <hr /> <div class="header-info"> <label class="">Employee Details</label> <button class="btn btn-default pull-right" data-toggle="modal" data-target="#AddModal" ng-click="clearModel()">Add Employee</button> </div> <hr /> <br /> <div class="alert alert-info" ng-if="message"> <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> {{message}} </div> <div class="table-data"> <table class="table table-bordered table-responsive table-hover"> <thead> <tr> <th>ID</th> <th>Full Name</th> <th>Email Address</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> <tr ng-repeat="names in employee"> <td>{{ names.ID }}</td> <td>{{ names.Name }}</td> <td>{{ names.Email }}</td> <td><button class="btn btn-info" data-toggle="modal" data-target="#EditModal" ng-click="selectUser(names)">Edit</button></td> <td><button class="btn btn-danger" ng-click="DeleteEmployee(names)">Delete</button></td> </tr> </tbody> </table> </div> <!-- Modal Add modal--> <div class="modal fade" id="AddModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form name="employee_form" data-ng-submit="AddEmployee()"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Add Employee Details</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="exampleInputEmail1">User Name</label> <input type="text" class="form-control" id="fullname" aria-describedby="emailHelp" placeholder="Enter Full Name" ng-model="model.Name" required="required"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" ng-model="model.Email" required="required"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-default pull-left">Save</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </form> </div> </div> </div> <!-- Edit modal--> <div class="modal fade" id="EditModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form name="employee_form" data-ng-submit="UpdateEmployee()"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Edit Employee Details</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="exampleInputEmail1">User Name</label> <input type="text" class="form-control" id="fullname" aria-describedby="emailHelp" placeholder="Enter FullName" ng-model="selectedUser.Name" required="required"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" ng-model="selectedUser.Email" required="required"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-default pull-left">Save</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </form> </div> </div> </div> </div> <script> var app = angular.module('HomeApp', []); app.controller('HomeController', function ($scope, $http) { $scope.model = @Html.Raw(Json.Encode(Model)) $http({ method: 'GET', url: '@Url.Action("getEmployee", "Home")', headers: { 'Content-type': 'application/json' } }).then(function (response) { debugger; $scope.employee = JSON.parse(response.data); }, function (error) { console.log(error); }); $scope.AddEmployee = function () { debugger; var eee = $scope.model; $http({ method: 'POST', url: '@Url.Action("AddEmployee", "Home")', data: $scope.model, headers: { 'Content-type': 'application/json' } }).then(function (response) { $scope.employee = JSON.parse(response.data); $scope.message = "Employee added Successfully"; $("#AddModal").modal("hide"); }, function (error) { console.log(error); }); } $scope.selectUser = function (names) { $scope.selectedUser = names; } $scope.UpdateEmployee = function () { var eee = $scope.selectedUser; $http({ method: 'POST', url: '@Url.Action("UpdateEmployee", "Home")', data: $scope.selectedUser, headers: { 'Content-type': 'application/json' } }).then(function (response) { $scope.employee = JSON.parse(response.data); $scope.message = "Employee updated Successfully"; $("#EditModal").modal("hide"); }, function (error) { console.log(error); }); } $scope.DeleteEmployee = function (names) { $http({ method: 'POST', url: '@Url.Action("DeleteEmployee", "Home")', data: names, headers: { 'Content-type': 'application/json' } }).then(function (response) { $scope.employee = JSON.parse(response.data); $scope.message = "Employee Deleted Successfully"; $("#EditModal").modal("hide"); }, function (error) { console.log(error); }); } $scope.clearModel = function () { $scope.model = null; } }); </script>

And we are done. Run your project and see if it works. You can comment below for technical questions about this article.

Thank you for reading!!

Happy Coding!!

Like this: Like Loading...