Let’s start this article.
First, we create an MVC project. Go to File-> New-> Project and select “ASP.NET Web Application”.
Now, select MVC template for the project.
In Solution Explorer window, we can see the structure of our project.
Now, we add the model classes in our project. We have an Employee table which we will use in our project and implement the CRUD operation on.
- CREATE TABLE [dbo].[Employee](
- [Emp_Id] [int] IDENTITY(1,1) NOT NULL,
- [Emp_Name] [varchar](max) NULL,
- [Emp_City] [varchar](max) NULL,
- [Emp_Age] [int] NULL,
- CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
- (
- [Emp_Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
-
- GO
For database CRUD operation, we will use the Entity Framework Data First approach. For this, right click on “Model” folder and click on “New Item” option.
Now, select “ADO.NET Entity Data Model” and name it as “EmployeeModel”.
Establish a connection with “SQL Server Database” Engine.
Select Employee table Entity Data Model Wizard and click on Finish button.
Now, go to your project’s Model folder where you can see that Employee Model class has been created. So, you have successfully created a connection with database.
After this, we download and install the AngularJS package. Right click on Project Name and select “Manage NuGet Packages” option and download the AngularJS packages.
In Scripts folder, you can find that AngularJS files have been installed successfully.
Now, we create the Employee Controller. So, right click on Controller Folder and create an empty Controller.
Now, copy and paste the following code into your Employee Controller section.
- using AngularCRUD.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace AngularCRUD.Controllers {
- public class EmployeeController: Controller {
-
- public ActionResult Index() {
- return View();
- }
-
-
-
-
-
- public JsonResult Get_AllEmployee() {
- using(DemoEntities Obj = new DemoEntities()) {
- List < Employee > Emp = Obj.Employees.ToList();
- return Json(Emp, JsonRequestBehavior.AllowGet);
- }
- }
-
-
-
-
-
- public JsonResult Get_EmployeeById(string Id) {
- using(DemoEntities Obj = new DemoEntities()) {
- int EmpId = int.Parse(Id);
- return Json(Obj.Employees.Find(EmpId), JsonRequestBehavior.AllowGet);
- }
- }
-
-
-
-
-
- public string Insert_Employee(Employee Employe) {
- if (Employe != null) {
- using(DemoEntities Obj = new DemoEntities()) {
- Obj.Employees.Add(Employe);
- Obj.SaveChanges();
- return "Employee Added Successfully";
- }
- } else {
- return "Employee Not Inserted! Try Again";
- }
- }
-
-
-
-
-
- public string Delete_Employee(Employee Emp) {
- if (Emp != null) {
- using(DemoEntities Obj = new DemoEntities()) {
- var Emp_ = Obj.Entry(Emp);
- if (Emp_.State == System.Data.Entity.EntityState.Detached) {
- Obj.Employees.Attach(Emp);
- Obj.Employees.Remove(Emp);
- }
- Obj.SaveChanges();
- return "Employee Deleted Successfully";
- }
- } else {
- return "Employee Not Deleted! Try Again";
- }
- }
-
-
-
-
-
- public string Update_Employee(Employee Emp) {
- if (Emp != null) {
- using(DemoEntities Obj = new DemoEntities()) {
- var Emp_ = Obj.Entry(Emp);
- Employee EmpObj = Obj.Employees.Where(x => x.Emp_Id == Emp.Emp_Id).FirstOrDefault();
- EmpObj.Emp_Age = Emp.Emp_Age;
- EmpObj.Emp_City = Emp.Emp_City;
- EmpObj.Emp_Name = Emp.Emp_Name;
- Obj.SaveChanges();
- return "Employee Updated Successfully";
- }
- } else {
- return "Employee Not Updated! Try Again";
- }
- }
- }
- }
After creating the Controller, now, we create a View. Right click on Index method and create an Empty View.
Paste the following code into the Index View:
- @{
- ViewBag.Title = "Index";
- }
-
- <style>
- .btn-space {
- margin-left: -5%;
- background-color: cornflowerblue;
- font-size: large;
- }
- </style>
- <h2>Index</h2>
- <div ng-app="myApp">
- <div ng-controller="myCtrl" ng-init="GetAllData()" class="divList">
- <p class="divHead">List of Employee</p>
- <table cellpadding="12" class="table table-bordered table-hover">
- <tr>
- <td>
- <b>ID</b>
- </td>
- <td>
- <b>Name</b>
- </td>
- <td>
- <b>City</b>
- </td>
- <td>
- <b>Age</b>
- </td>
- <td>
- <b>Actions</b>
- </td>
- </tr>
- <tr ng-repeat="Emp in employees">
- <td>
- {{Emp.Emp_Id}}
- </td>
- <td>
- {{Emp.Emp_Name}}
- </td>
- <td>
- {{Emp.Emp_City}}
- </td>
- <td>
- {{Emp.Emp_Age}}
- </td>
- <td>
- <input type="button" class="btn btn-warning" value="Update" ng-click="UpdateEmp(Emp)" />
- <input type="button" class="btn btn-danger" value="Delete" ng-click="DeleteEmp(Emp)" />
- </td>
- </tr>
- </table>
- <div class="form-horizontal" role="form">
- <div class="container">
- <div class="row">
- <h2>
- <span id="spn">Add New Employee</span>
- </h2>
- </div>
- <div class="row">
- <div class="col-sm-6 col-lg-4">
- <div class="form-group">
- <label class="col-md-4 control-label">Name:</label>
- <div class="col-md-8">
- <input type="text" class="form-control" id="inputEmail" placeholder="Name" ng-model="EmpName">
- </div>
- </div>
- </div>
- <div class="col-sm-6 col-lg-4">
- <div class="form-group">
- <label class="col-md-4 control-label">City:</label>
- <div class="col-md-8">
- <input type="text" class="form-control" id="inputPassword" placeholder="City" ng-model="EmpCity">
- </div>
- </div>
- </div>
- <div class="col-sm-6 col-lg-4">
- <div class="form-group">
- <label class="col-md-4 control-label">Age:</label>
- <div class="col-md-8">
- <input type="text" class="form-control" id="inputLabel3" placeholder="Age" ng-model="EmpAge">
- </div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-sm-6 col-lg-4">
- <input type="button" id="btnSave" class="form-control btn-space" value="Submit" ng-click="InsertData()" />
- </div>
- </div>
- </div>
- </div>
- </div>
- @Html.Hidden("EmpID_")
-
- </div>
For CRUD operations in AngularJS, we create a JavaScript file, write the code into that file, and implement this file into our Index View.
First, create a JavaScript file and copy the following code.
JavaScript code - var app = angular.module("myApp", []);
- app.controller("myCtrl", function($scope, $http) {
- debugger;
- $scope.InsertData = function() {
- var Action = document.getElementById("btnSave").getAttribute("value");
- if (Action == "Submit") {
- $scope.Employe = {};
- $scope.Employe.Emp_Name = $scope.EmpName;
- $scope.Employe.Emp_City = $scope.EmpCity;
- $scope.Employe.Emp_Age = $scope.EmpAge;
- $http({
- method: "post",
- url: "http://localhost:39209/Employee/Insert_Employee",
- datatype: "json",
- data: JSON.stringify($scope.Employe)
- }).then(function(response) {
- alert(response.data);
- $scope.GetAllData();
- $scope.EmpName = "";
- $scope.EmpCity = "";
- $scope.EmpAge = "";
- })
- } else {
- $scope.Employe = {};
- $scope.Employe.Emp_Name = $scope.EmpName;
- $scope.Employe.Emp_City = $scope.EmpCity;
- $scope.Employe.Emp_Age = $scope.EmpAge;
- $scope.Employe.Emp_Id = document.getElementById("EmpID_").value;
- $http({
- method: "post",
- url: "http://localhost:39209/Employee/Update_Employee",
- datatype: "json",
- data: JSON.stringify($scope.Employe)
- }).then(function(response) {
- alert(response.data);
- $scope.GetAllData();
- $scope.EmpName = "";
- $scope.EmpCity = "";
- $scope.EmpAge = "";
- document.getElementById("btnSave").setAttribute("value", "Submit");
- document.getElementById("btnSave").style.backgroundColor = "cornflowerblue";
- document.getElementById("spn").innerHTML = "Add New Employee";
- })
- }
- }
- $scope.GetAllData = function() {
- $http({
- method: "get",
- url: "http://localhost:39209/Employee/Get_AllEmployee"
- }).then(function(response) {
- $scope.employees = response.data;
- }, function() {
- alert("Error Occur");
- })
- };
- $scope.DeleteEmp = function(Emp) {
- $http({
- method: "post",
- url: "http://localhost:39209/Employee/Delete_Employee",
- datatype: "json",
- data: JSON.stringify(Emp)
- }).then(function(response) {
- alert(response.data);
- $scope.GetAllData();
- })
- };
- $scope.UpdateEmp = function(Emp) {
- document.getElementById("EmpID_").value = Emp.Emp_Id;
- $scope.EmpName = Emp.Emp_Name;
- $scope.EmpCity = Emp.Emp_City;
- $scope.EmpAge = Emp.Emp_Age;
- document.getElementById("btnSave").setAttribute("value", "Update");
- document.getElementById("btnSave").style.backgroundColor = "Yellow";
- document.getElementById("spn").innerHTML = "Update Employee Information";
- }
- })
Now, provide the references of AngularJS and AngularCode file that we created into Index View.
Now, I think our project is ready to work. So, let’s run the application. Press F5 and you can see that following screen will be visible on your browser.
Now, we will learn about all CRUD operations (create, read, update and delete) and understand how they work.
Get all Employee Record
When we run the application, at first, all employees records will retrieve and show up in the grid. You can see that in “ng-init” directive, we call the “getAllData” record. This method is responsible for retrieval of all the records.
In “AngularCode” file you can find this method.
In “GetAllData” method, we used the $http service of AngularJS and call the “Get_AllEmployee” method of “Employee” controller. Code of “Get_AllEmployee” method is the following.
In this method, we get all employees' records from “Employee” entity and pass as JSON result.
Add New Employee
When we click on “Submit” button, the “InsertData” method will be call.
In this method, we retrieve the data from Name, City, and Age field and insert into “Employe” object . We call the “Insert_Employee” method of Employee Controller and Pass the “Employe” object as parameter.
In controller section, we add the “Employe” object into Employee entity.
And pass the Confirmation message as confirmation. Now, you can see that the record of “Sandeep” is added successfully.
Delete The Employee Record
We are using ng-repeat directive and inserting Employee Name, Age, Id and City information into table. You can see that we are creating on extra column(“Action”). In this column, we are adding two buttons for “Delete” and “Update” command and on ng-click directive, we are calling “DeleteEmp” method for deleting operation and “UpdateEmp” for update operation. In both methods, we are passing the Object of Employee.
In “DeleteEmp” method, we are calling the “Delete_Employee” of controller using “$http”,
In “Delete_Employee” method, we are removing the Employee record from “Employee” table.
Let’s try to delete the record of “Pardeep” Employee.
Update Employee Record
In Update command, we are calling the “UpdateEmp” method in which we are inserting the information of employee into textboxes and changing the properties of button and span section.
Let’s click on Update button for employee “Nitin”.
Now, we change the name and City for this employee.
When we click on “Update” button, then “InsertData” method of AngularCode file we will be called and “else” section will execute because the value of the button is not equal to “Submit”.
In the above code, we are calling the “Update_Employee” method of Controller. In “Update_Employee” method, we update the record for employee and send the confirmation message.
You can check that information for employee “Nitin” has been updated.
I hope you liked the article. Thanks to read the article. If you have any doubt our query, then leave it in the comment section.