CRUD operations using angular js and webapi with Bootstrap ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Tuesday, 7 June 2016

CRUD operations using angular js and webapi with Bootstrap

22:52:00 Posted by raviteja swayampu , , , 5 comments
Hi everyone again in this tutorial i am going to explain CRUD(Create,Read,Update,Delete) operations using Angular js and web API. And i also used bootstrap to beautify the UI with popup models.I used Angular Services($http) to communicate with API server.They are already discussed in previous tutorials below.


Those are the angular js introduction tutorials.I explained one by one concept through tutorials in practical way.The output of the applications is like below screen shot.

CRUD operations using angular js and MVC 5

CRUD operations using Angular steps

Create MVC application and setup angular js

1.Create ASP.NET MVC application using VS 2013(VS2013 or higher versions are recommend).
2.If you don't know how to setup angular refer angular setup in MVC here.
3.Add a table in the database.(here i named it as Employee table).

CRUD operations using angular js and MVC 5

Add ADO.NET Entity Data Model

1.Right click on Models folder--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next 
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish. 
4.Now Model is added to my project.


Create Web API controller

1.Right click on Controllers folder --> Add --> Controller --> Select "Wep API2 controller actions with Entity framework" --> click Add --> name the controller(i named it as EmployeeAPIController) --> Select Model and context class in Add Controller popup wizard --> finally click Add button.
2.Following code is generated by Visual studio.
3.EmployeeAPIController.cs
using WebAPICRUDwithBootstrap.Models;
namespace WebAPICRUDwithBootstrap.Controllers
{
    public class EmployeeAPIController : ApiController
    {
        private DatabaseEntities db = new DatabaseEntities();

        // GET api/EmployeeAPI
        public IQueryable GetEmployees()
        {
            return db.Employees;
        }
        // GET api/EmployeeAPI/5
        [ResponseType(typeof(Employee))]
        public IHttpActionResult GetEmployee(int id)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return NotFound();
            }

            return Ok(employee);
        }

        // PUT api/EmployeeAPI/5
        public IHttpActionResult PutEmployee(int id, Employee employee)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != employee.EmpNo)
            {
                return BadRequest();
            }

            db.Entry(employee).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST api/EmployeeAPI
        [ResponseType(typeof(Employee))]
        public IHttpActionResult PostEmployee(Employee employee)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Employees.Add(employee);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = employee.EmpNo }, employee);
        }

        // DELETE api/EmployeeAPI/5
        [ResponseType(typeof(Employee))]
        public IHttpActionResult DeleteEmployee(int id)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return NotFound();
            }
            db.Employees.Remove(employee);
            db.SaveChanges();

            return Ok(employee);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool EmployeeExists(int id)
        {
            return db.Employees.Count(e => e.EmpNo == id) > 0;
        }
    }


4.The above code is generated by Visual studio.We call this methods using uri (Ex: /api/EmployeeAPI/)
5.please refer previous post for understanding Web API. Introduction to Web API in MVC5.
Note: 
a).Like Controller classes API classes also post fixed with Controller.But API controller classes are inherited from APIController base class.
b).After adding Web API controller we need to modify Global.asax file for working of web API in MVC application.Goto Global.asax --> Add using System.Web.Mvc.Http; name space and configure web API by adding below line of code in Application_Start() method.
//conigure web API
GlobalConfiguration.Configure(WebApiConfig.Register);


Add angular Module,controller and services js files

1.Right  click on Scripts folder and Add CRUDScripts folder to add angular scripts to the project.
2.create Model.js,Controller.js and Service.js files in CRUDScripts folder.
3.Replace the Module.js file code with below code.
Module.js
//Angular module creation using angular.module method.
//It acts as a auto bootstraper for angular application.
//We bind this module to view using ng-app directive.
var myapp;
(function () {
    myapp = angular.module('myangularapp', []);
})();

4.Replace Controller.js file with below code..
//Angular controller 
myapp.controller('crudcontroller', function ($scope, crudservice) {
    
    //Loads all Employee records when page loads
    loadEmployees();
    function loadEmployees() {
        var EmployeeRecords = crudservice.getAllEmployees();
        EmployeeRecords.then(function (d) {     //success
            $scope.Employees = d.data;
        },
        function(){
            swal("Oops..","Error occured while loading","error"); //fail
        });
    }

    //save form data
    $scope.save = function () {
        //debugger;
        var Employee = {
            EmpNo:$scope.EmpNo,
            EmpName: $scope.EmpName,
            Salary: $scope.Salary,
            DeptName: $scope.DeptName,
            Designation: $scope.Designation
        };
        var saverecords = crudservice.save(Employee);
        saverecords.then(function (d) {
            $scope.EmpNo = d.data.EmpNo;
            loadEmployees();
            swal("Reord inserted successfully");
        },
        function(){
            swal("Oops..","Error occured while saving",'error');
        });
    }

    //get single record by ID

    $scope.get = function (Employee) {
        //debugger;
        var singlerecord = crudservice.get(Employee.EmpNo);
        singlerecord.then(function (d) {
           // debugger;
            var record = d.data;
            $scope.UpdateEmpNo = record.EmpNo;
            $scope.UpdateEmpName = record.EmpName;
            $scope.UpdateSalary = record.Salary;
            $scope.UpdateDeptName = record.DeptName;
            $scope.UpdateDesignation = record.Designation;
        },
        function(){
            swal("Oops...","Error occured while getting record","error");
        });
    }

    //update Employee data
    $scope.update = function () {
        //debugger;
        var Employee = {
            EmpNo: $scope.UpdateEmpNo,
            EmpName: $scope.UpdateEmpName,
            Salary: $scope.UpdateSalary,
            DeptName: $scope.UpdateDeptName,
            Designation:$scope.UpdateDesignation
        };
        debugger;
        var updaterecords = crudservice.update($scope.UpdateEmpNo, Employee);
        updaterecords.then(function (d) {
            loadEmployees();
            swal("Record updated successfully");
        },
        function () {
            swal("Opps...","Error occured while updating","error");
        });
    }

    //delete Employee record
    $scope.delete = function (UpdateEmpNo) {
        debugger;
        var deleterecord = crudservice.delete($scope.UpdateEmpNo);
        deleterecord.then(function (d) {
            var Employee = {
                EmpNo: '',
                EmpName: '',
                Salary: '',
                DeptName: '',
                Designation: ''
            };
            loadEmployees();
            swal("Record deleted succussfully");
        });
    }
});

5.loadEmployees() method loads all the Employees after page loads.
6.crudservice communicates with server and gets data.
7.Here instead of javascript alerts i used a Sweet alert plugin to beautify the traditional java script alerts.

8.Finally replace the Service.js file code with below one..
//Service to get data from service..
myapp.service('crudservice', function ($http) {
    
    this.getAllEmployees = function () {
        return $http.get("/api/EmployeeAPI");
    }

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

    //get single record by Id
    this.get = function (EmpNo) {
        //debugger;
        return $http.get("/api/EmployeeAPI/"+EmpNo);
    }

    //update Employee records
    this.update = function (UpdateEmpNo, Employee) {
        //debugger;
        var updaterequest = $http({
            method: 'put',
            url: "/api/EmployeeAPI/" +UpdateEmpNo,
            data:Employee
        });
        return updaterequest;
    }

    //delete record
    this.delete = function (UpdateEmpNo) {
        debugger;
        var deleterecord= $http({
            method: 'delete',
            url: "/api/EmployeeAPI/" + UpdateEmpNo
        });
        return deleterecord;
    }
});

Create View to display the CRUD application UI.

1.Add controller --> name it as HomeController.cs .
2.Create Index action method and add View to it by Right click on Index action --> Add View --> Add.
3.Replace Index View code with below code(it  looks a little bit complex but it is easy).
@{
    ViewBag.Title = "Mitechdev.com";
}

<style>

    input,label{
        margin-left:20px;
    }
</style>

@*Display Employee datain Table format*@

<div class="container" ng-controller="crudcontroller">
    <div class="panel panel-primary">
        <div class="panel-heading">
            Angular Grid
        </div>
        <div class="panel-body">
            <button type="button" class="btn btn-info" data-target="#AddNew" data-toggle="modal">Add New</button><br />

            @*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">&times;</button>
                            <h3 class="text-info">Add New Employee</h3>
                        </div>
                        <div class="modal-body">
                            @*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" required />
                                </div>
                                <div class="form-group">
                                    <label class="text-info"> Employee Name</label>
                                    <input class="form-control" name="EmpName" ng-model="EmpName" type="text" placeholder="Employee Name" required />
                                </div>
                                <div class="form-group">
                                    <label class="text-info"> Salary</label>
                                    <input class="form-control" name="Salary" ng-model="Salary" type="number" placeholder="Salary" required />
                                </div>
                                <div class="form-group">
                                    <label class="text-info"> Dept Name</label>
                                    <input class="form-control" name="DeptName" ng-model="DeptName" type="text" placeholder="Dept Name" required />
                                </div>
                                <div class="form-group">
                                    <label class="text-info"> Designation</label>
                                    <input class="form-control" name="Designation" ng-model="Designation" type="text" placeholder="Designation" required />
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-success" id="btnSave" data-dismiss="modal" ng-click="save()">Save</button>
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        @*Employee Records*@

        <table class="table table-bordered">
            <thead style="background-color:lightgreen;">
                <tr>
                    <th> Emp Name</th>
                    <th> Emp Name</th>
                    <th>Salary </th>
                    <th>Dept Name</th>
                    <th>Designation</th>
                    <th> Actions</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="emp in Employees">
                    <td> {{emp.EmpNo}}</td>
                    <td> {{emp.EmpName}} </td>
                    <td>{{emp.Salary}}</td>
                    <td>{{emp.DeptName}}</td>
                    <td>{{emp.Designation}}</td>
                    <td style="width:200px;">
                        <a href="#" class="btn btn-info" data-toggle="modal" data-target="#Update" ng-click="get(emp)">Update</a>
                        <a href="#" class="btn btn-danger" id="btnDelete" data-toggle="modal" data-target="#deleteDialog" ng-click="get(emp)">Delete</a>
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="panel-footer">
            Microsoft tech Developments
        </div>

        @*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">&times;</button>
                        <h3 class="text-info">Update Existing Employee</h3>
                    </div>
                    <div class="modal-body">
                        @*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" required />
                            </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" required />
                            </div>
                            <div class="form-group">
                                <label class="text-info"> Salary</label>
                                <input class="form-control" name="Salary" ng-model="UpdateSalary" type="number" placeholder="Salary" required />
                            </div>
                            <div class="form-group">
                                <label class="text-info"> Dept Name</label>
                                <input class="form-control" name="DeptName" ng-model="UpdateDeptName" type="text" placeholder="Dept Name" required />
                            </div>
                            <div class="form-group">
                                <label class="text-info"> Designation</label>
                                <input class="form-control" name="Designation" ng-model="UpdateDesignation" type="text" placeholder="Designation" required />
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-success" 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>

        @*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">&times;</button>
                        <h3 class="text-info">Are you sure you want to delete the record?</h3>
                    </div>
                    <div class="modal-body">
                        <div>
                            <p>EmpNo:{{UpdateEmpNo}}</p>
                            <p>EmpName:{{UpdateEmpName}}</p>
                            <p>Salary:{{UpdateSalary}}</p>
                            <p>DeptName:{{UpdateDeptName}}</p>
                            <p>Designation:{{UpdateDesignation}}</p>
                        </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>


    </div>
</div>

@section scripts{
<script src="~/Scripts/CRUDScripts/Controller.js"></script>
<script src="~/Scripts/CRUDScripts/Service.js"></script>
<script>
    //sweet alert script starts here...
    //document.querySelector("#btnSave").onclick = function () {
    //    swal("Employee Record inserted successfully");
    //}
    //document.querySelector("#btnDelete").onclick = function () {
    //    swal({
    //        title: "Are you sure want to delete?",
    //        text: "The record will be deleted permanetly",
    //        type: "warning",
    //        showCancelButton: true,
    //        confirmButtonColor: "#DD6B55",
    //        confirmButtonText: "Yes, delete it!"
    //    });
    //};
</script>
}

4.Don't forget to add script references of Controller.js,Module.js and Service.js in application.
5.Now run the application and check it once..

Add new Employee window

CRUD operations using angular js and MVC 5-add new record

update Employee window popup


CRUD operations using angular js and MVC 5

Delete Employee Window popup


delete alert to remove record

I hope this tutorial will helpful for every one working on angular js and who willing to learn angular js.
Download code from here Source Code

Conclusion


I hope this tutorial may helpful for many readers.Please subscribe to this blog www.mitechdev.com to get posts to your mail inbox.And follow through social networks(Facebook,twitter,google plus) for daily updates...


5 comments:

  1. Hi. thanks for the tutorial.

    i want to ask, how to move database to real database server ( not local db ) ?

    Thanks

    ReplyDelete
    Replies
    1. In real time the Database people will take a backup the DB and run in another server..
      follow below link..
      http://www.mytechmantra.com/LearnSQLServer/How-to-Backup-Database-SQL-Server-P1.html

      Delete
    2. Thank You,

      I try this tutorial using Local DB, it's great work...
      But when i try to connect to real server ( MS-SQL Server), it's not work..

      have some different to connect local DB or Real Server ?

      Delete
    3. I'm sorry, it's my mistake

      I re try to make connection to real server, and work..
      thank you

      Delete
  2. Hi. thanks for the tutorial
    may i know how to validations using anjulaJs with out using form

    ReplyDelete