AngularJS CRUD Using ASP.NET MVC5 – CREATE, UPDATE and DELETE Employee Data


In Previous article we setup Visual Studio 2015 project for AngularJS  and performed read operation on Employee Table. In this article, we will see how to CREATE, UPDATE and DELETE Employee  data.

You can download code for previous article from GitHub and start adding code for CREATE, UPDATE and DELETE Employee data.

So Let us start coding 🙂

Step-1: CREATE Operation – Add new employee data

First, we need to add new method Insert in EmployeeController which will add employee entity into SQL database. So Let us add following code in Controllers –> EmployeeController.cs:

//POST Employee/AddEmployee
[HttpPost]
public JsonResult Insert(Employee employee)
{
    if (employee != null)
    {
        using (LearningDBEntities db = new LearningDBEntities())
        {
            db.Employees.Add(employee);
            db.SaveChanges();
            return Json(new { success = true });
        }
    }
    else
    {
        return Json(new { success = false });
    }
}

Above code will Insert employee details into database, which is returning a JSON result of boolean data type. If it’s true then it indicate that data inserted to database successfully.

Second, we need to add following code in AngularJSApp–> Employee–> Service.js file which call MVC EmployeeController’s Insert method using $http.post method:

//add new employee
this.save = function (Employee) {
    var request = $http({
        method: 'post',
        url: '/Employee/Insert',
        data: Employee
    });
    return request;
}

Third, we need to add following code in AngularJSApp–> Employee–> Controller.js file which will call angular employeeService –> save method. once save is successful we are resetting $scope objects and reloading employee data to display new record in list.

//save employee data
$scope.save = function () {
    var Employee = {
        EmpNo: $scope.EmpNo,
        EmpName: $scope.EmpName,
        Email: $scope.Email,
        DeptName: $scope.DeptName,
        Designation: $scope.Designation
    };
    var saverecords = employeeService.save(Employee);
    saverecords.then(function (d) {
        if (d.data.success === true) {
            loadEmployees();
            alert("Employee added successfully");
            $scope.resetSave();
        }
        else { alert("Employee not added."); }
    },
    function () {
        alert("Error occurred while adding employee.");
    });
}
//reset controls after save operation
$scope.resetSave = function () {
    $scope.EmpNo = '';
    $scope.EmpName = '';
    $scope.Email = '';
    $scope.DeptName = '';
    $scope.Designation = '';
}

Finally, we need to add following html code in Views–> Home–> Index.cshtml file which will help us to submit form data using ng-controller and ng-model binding and later on this $scope object values will be used by $scope.save method to save the data:

@*New record Modal addition..*@
<div class="modal" id="AddNew" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
     <button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="text-info">Add New Employee</h3>
</div>
<div class="modal-body" style="margin-left:20px">
   @*Add New Employee form starts here...*@
<form class="form-horizontal" name="AddNewForm" >
<div class="form-group">
   <input class="form-control" readonly="readonly"
name="EmpNo" ng-model="EmpNo" type="hidden"
placeholder="Employee Number" />
</div>
<div class="form-group">
<label class="control-label"> Employee Name</label>
   <input class="form-control" name="EmpName"
ng-model="EmpName" type="text"
placeholder="Employee Name" />
</div>
<div class="form-group">
   <label class="control-label"> Email</label>
   <input class="form-control" name="Email"
ng-model="Email" type="email" placeholder="Email" />
</div>
<div class="form-group">
    <label class="control-label"> Department Name</label>
    <input class="form-control" name="DeptName"
ng-model="DeptName" type="text"
placeholder="Dept Name" />
</div>
<div class="form-group">
   <label class="control-label"> Designation</label>
   <input class="form-control" name="Designation"
ng-model="Designation" type="text"
placeholder="Designation" />
</div>
</form></div>
<div class="modal-footer">
   <button type="button" class="btn btn-primary"
id="btnSave" data-dismiss="modal" ng-click="save()">Save</button>
   <button type="button" class="btn btn-default"
data-dismiss="modal" ng-click="resetSave()">Close</button></div>
</div>
</div>
</div>

Next, let us add code for update operation.

Step-2: UPDATE Operation – Update existing employee data

First, we need to add new method Update  in EmployeeController which will update employee entity into SQL database. So Let us add following code in Controllers –> EmployeeController.cs:

//POST Employee/Update
[HttpPost]
public JsonResult Update(Employee updatedEmployee)
{
    using (LearningDBEntities db = new LearningDBEntities())
    {
        Employee existingEmployee = db.Employees.Find(updatedEmployee.EmpID);
        if (existingEmployee == null)
        {
            return Json(new { success = false });
        }
        else
        {
            existingEmployee.EmpName = updatedEmployee.EmpName;
            existingEmployee.DeptName = updatedEmployee.DeptName;
            existingEmployee.Email = updatedEmployee.Email;
            existingEmployee.Designation = updatedEmployee.Designation;
            db.SaveChanges();
            return Json(new { success = true });
        }
    }
}

Above code will update existing employee details in database that is selected to update, which is also returning a JSON result of boolean data type. As previously If it’s true then it indicate that data updated to database successfully.

Second, we need to add following code in AngularJSApp–> Employee–> Service.js file which call MVC EmployeeController’s Update method using angular $http.post:

//update Employee records
this.update = function (Employee) {
    var updaterequest = $http({
        method: 'post',
        url: '/Employee/Update',
        data: Employee
    });
    return updaterequest;
}

Third, we need to add following code in AngularJSApp–> Employee–> Controller.js file which will call angular employeeService->update method. once data updated successfully we are resetting $scope objects and reloading employee data to display updated record in list.

//update Employee data
$scope.update = function () {
    var Employee = {
        EmpID: $scope.UpdateEmpNo,
        EmpName: $scope.UpdateEmpName,
        Email: $scope.UpdateEmail,
        DeptName: $scope.UpdateDeptName,
        Designation: $scope.UpdateDesignation
    };
    var updaterecords = employeeService.update(Employee);
    updaterecords.then(function (d) {
        if (d.data.success === true) {
            loadEmployees();
            alert("Employee updated successfully");
            $scope.resetUpdate();
        }
        else {
            alert("Employee not updated.");
        }
    },
    function () {
        alert("Error occured while updating employee record");
    });
}
//reset controls after update
$scope.resetUpdate = function () {
    $scope.UpdateEmpNo = '';
    $scope.UpdateEmpName = '';
    $scope.UpdateEmail = '';
    $scope.UpdateDeptName = '';
    $scope.UpdateDesignation = '';
}

Finally, we need to add following html code in Views–> Home–> Index.cshtml file which will help us to submit form data using ng-controller and ng-model binding and later on this $scope object values will be used by $scope.update method to update the employee data:

@*Upadate Employee records*@
<div class="modal" id="Update" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
  <button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="text-info">Update Existing Employee</h3>
</div>
<div class="modal-body" style="margin-left:20px">
 @*Update Employee form starts here...*@
<form class="form-horizontal" name="UpdateEmployeeForm">
<div class="form-group">
  <input class="form-control" readonly="readonly" name="EmpNo"
ng-model="UpdateEmpNo" type="hidden" placeholder="Employee Number" />
</div>
<div class="form-group">
  <label class="text-info"> Employee Name</label>
  <input class="form-control" name="EmpName" ng-model="UpdateEmpName"
type="text" placeholder="Employee Name" />
</div>
<div class="form-group">
  <label class="text-info"> Email</label>
  <input class="form-control" name="Email" ng-model="UpdateEmail"
type="email" placeholder="Email" />
</div>
<div class="form-group">
  <label class="text-info"> Department Name</label>
  <input class="form-control" name="DeptName" ng-model="UpdateDeptName"
type="text" placeholder="Dept Name" />
</div>
<div class="form-group">
  <label class="text-info"> Designation</label>
  <input class="form-control" name="Designation"
ng-model="UpdateDesignation" type="text"
placeholder="Designation" />
</div>
</form></div>
<div class="modal-footer">
  <button type="button" class="btn btn-primary" id="btnUpdate"
data-dismiss="modal" ng-click="update()">
     Update
   </button>
   <button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Next, let us add code for delete operation.

Step-3: DELETE Operation – Delete employee data

First, we need to add new method Delete in EmployeeController which will Delete employee entity. So Let us add following code in Controllers –> EmployeeController.cs:

//POST Employee/Delete/1
[HttpPost]
public JsonResult Delete(int id)
{
    using (LearningDBEntities db = new LearningDBEntities())
    {
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return Json(new { success = false });
        }
        db.Employees.Remove(employee);
        db.SaveChanges();
        return Json(new { success = true });
    }
}

Above code will delete existing employee details from database that is selected to delete, which is also returning a JSON result of boolean data type. If it’s true then it indicate that data deleted from database successfully.

Second, we need to add following code in AngularJSApp–> Employee–> Service.js file which call MVC EmployeeController’s Delete method using angular  $http.post method:

//delete record
this.delete = function (UpdateEmpNo) {
    return $http.post('/Employee/Delete/' + UpdateEmpNo);
}

Third, we need to add following code in AngularJSApp–> Employee–> Controller.js file which will call angular employeeService –> delete method. once delete is successful we are reloading employee data to display updated list.

//delete Employee record
$scope.delete = function (UpdateEmpNo) {
    var deleterecord = employeeService.delete($scope.UpdateEmpNo);
    deleterecord.then(function (d) {
        if (d.data.success === true) {
            loadEmployees();
            alert("Employee deleted succussfully");
        }
        else {
            alert("Employee not deleted.");
        }
    });
}

Finally, we need to add following html code in Views–> Home–> Index.cshtml file which will bind $scope variables using angular expression {{variable}}.

@*Delete Employee record*@
<div class="modal" role="dialog" id="deleteDialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
  <button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="text-info">Are you sure you want to delete the record?</h3>
</div>
<div class="modal-body">
<div>
   Employee ID : {{UpdateEmpNo}}
   Empployee Name : {{UpdateEmpName}}</div>
</div>
<div class="modal-footer">
   <button type="button" class="btn btn-danger"
data-dismiss="modal"
ng-click="delete(UpdateEmpNo)">Delete Record</button>
   <button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Next, let us update and add code to call ng-click events for Delete/Update operation from buttons.

Step-4: Integrate UPDATE and DELETE button for operations

First, we need to update the button html tags for ng-click events in Views–> Home–> Index.cshtml as per below:

<td style="width:200px;">
  <a href="#" class="btn btn-info" data-toggle="modal"
data-target="#Update" ng-click="getForUpdate(emp)">Update</a>
  <a href="#" class="btn btn-danger" id="btnDelete" data-toggle="modal"
data-target="#deleteDialog" ng-click="getForDelete(emp)">Delete</a></td>

Then add following angular events (getForUpdate & getForDelete) for Update/Delete button click events in AngularJSApp–> Employee–> Controller.js file:

//get single record by ID
$scope.getForUpdate = function (Employee) {
    $scope.UpdateEmpNo = Employee.EmpID;
    $scope.UpdateEmpName = Employee.EmpName;
    $scope.UpdateEmail = Employee.Email;
    $scope.UpdateDeptName = Employee.DeptName;
    $scope.UpdateDesignation = Employee.Designation;
}

//get data for delete confirmation
$scope.getForDelete = function (Employee) {
    $scope.UpdateEmpNo = Employee.EmpID;
    $scope.UpdateEmpName = Employee.EmpName;
}

Above $scope variables are used during data-binding of employee properties when model dialog open for Update/Delete operation.

That’s all. we are all set to run the application now.

Step-5: Run the web application – F5

step-f5-run

Press Add Employee button, it will open model dialog.

step-16-Add-model

Add the details for employee and press save button. currently we are not using any data validation during insert/update operation but in next article we will see how to validation form data before saving it. Once data is saved, it will show alert of operation.

step-17-add-success

Currently we are using simple JavaScript alert to display notification messages for each operations. but in up coming article we will add toaster notification for sexy and beautiful alerts.

Next, let us update any employee data, press Update button for employee you want to update.

step-18-update-model

Update the field values and press Update button to save the data. It will display alert for successful update operation.

step-19-update-success

Now, let us delete employee, it will ask for confirmation before deleting the record

step-20-delete-model

once you confirm, it will delete the record by showing alert.

step-21-delete-success

After deletion, employee list will look like

step-22-after-delete-grid

That’s all for this article. In next article we will add some data validation for insert/update operation using AngularJS. Till than stay tuned 🙂

Please feel free to provide your feedback and comments.

Code for this article is available on GitHub:

Advertisements

One thought on “AngularJS CRUD Using ASP.NET MVC5 – CREATE, UPDATE and DELETE Employee Data

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s