Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Angular js with ASP.NET MVC Insert,Update, Delete

0.00/5 (No votes)
7 Nov 2015 1  
Angular js with ASP.NET MVC is more popular now days and for beginners, I will tell you what is angular js and show you a practical example of ASP.NET MVC for inserting, deleting and displaying data using angular js.

Introduction

AngularJS with ASP.NET MVC is more popular now days and for beginners, I will tell you what is AngularJS and show you a practical example of ASP.NET MVC for inserting, deleting and displaying data using AngularJS.

Basically, this article will demonstrate with example the following:

  • Step by step procedure to create ASP.NET MVC project with AngularJS
  • How to install AngularJS package in ASP.NET MVC project
  • How to create module, service and controller in AngularJS
  • How to get data from server side(C#)
  • How to bind/Load/Fill data from Server side to HTML page using AngularJS
  • How to perform insert, edit, update and delete operation on view using AngularJS data binding

What is AngularJS

AngularJS is a structural framework for dynamic web applications. You can create Single page application by using AngularJS . AngularJS provides data binding features in HTML page. AngularJS code is unit testable. AngularJS provides developers options to write client side application in a MVC way.

Advantages Of AngularJS

  1. Data Binding
  2. Scope
  3. Controllers
  4. Services
  5. Unit Testable Code
  6. Depedency Injection
  7. Single Page Application
  8. Developed by Google

Limitations Of AngularJS

1. Not Secure :

As all the code is written in JavaScript, Server side authentication and authorization is must

2. Not degradable :

If browser JavaScript is off, AngularJS can not work .

3. LifeCycle is Complex :

Lifcycle of AngularJS application is complex.

What You Need

As all of you have visual studio 2012 so that I am using visual studio 2012 with ASP.NET MVC 4.

Let's Get Started

Ok, first of all, you have to create a new ASP.NET MVC project by selecting New Project in Visual Studio 2012... on the start screen, then drill down to Templates => Visual C# => Web => ASP.NET MVC 4 Web Application and can name it as you prefer.

Select basic ASP.NET MVC 4 project template

Include Angular in our project via Nuget packages, you can also download it from angular website. We have to install AngularJS package to our project for this please does below steps

Open the Package manager Console from View => Other Windows => Package Manager Console as shown below:

  1. Install AngularJS package by using below command

  2. As AngularJS Route package is not come with AngularJS we have to install separate package for AngularJS route. so please Install AngularJS package by using below command

Step 1: Create Model in MVC project

As all of you knows that in MVC we have model for database record we will create first Model using entity framework

Create Employee table with this schema. ID is primary key and it is Identity

Add new Entity Data Model using Entity framework in Models folder

Select Database name from dropdown

Now We have model class for Employee .

Step 2: Create Controller in MVC project

Add new controller named as HomeController

Add below methods to HomeController

public ActionResult Index()
      {
          return View();
      }

      public JsonResult getAll()
      {
          using (SampleDBEntities dataContext = new SampleDBEntities())
          {
              var employeeList = dataContext.Employees.ToList();
              return Json(employeeList, JsonRequestBehavior.AllowGet);
          }
      }

      public JsonResult getEmployeeByNo(string EmpNo)
      {
          using (SampleDBEntities dataContext = new SampleDBEntities())
          {
              int no = Convert.ToInt32(EmpNo);
              var employeeList = dataContext.Employees.Find(no);
              return Json(employeeList, JsonRequestBehavior.AllowGet);
          }
      }
      public string UpdateEmployee(Employee Emp)
      {
          if (Emp != null)
          {
              using (SampleDBEntities dataContext = new SampleDBEntities())
              {
                  int no = Convert.ToInt32(Emp.Id);
                  var employeeList = dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();
                  employeeList.name = Emp.name;
                  employeeList.mobil_no = Emp.mobil_no;
                  employeeList.email = Emp.email;
                  dataContext.SaveChanges();
                  return "Employee Updated";
              }
          }
          else
          {
              return "Invalid Employee";
          }
      }
      public string AddEmployee(Employee Emp)
      {
          if (Emp != null)
          {
              using (SampleDBEntities dataContext = new SampleDBEntities())
              {
                  dataContext.Employees.Add(Emp);
                  dataContext.SaveChanges();
                  return "Employee Updated";
              }
          }
          else
          {
              return "Invalid Employee";
          }
      }

      public string DeleteEmployee(Employee Emp)
      {
          if (Emp != null)
          {
              using (SampleDBEntities dataContext = new SampleDBEntities())
              {
                  int no = Convert.ToInt32(Emp.Id);
                  var employeeList = dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();
                  dataContext.Employees.Remove(employeeList);
                  dataContext.SaveChanges();
                  return "Employee Deleted";
              }
          }
          else
          {
              return "Invalid Employee";
          }
      }

In the above class we have following methods

  1. getAll() Method will return all the emloyees in JSON format
  2. getEmployeeByNo() Method will return employee details by employee number
  3. UpdateEmployee() method will update existing employee details
  4. AddEmployee() method will add new employee to database
  5. DeleteEmployee() method will delete existing employee

Now we have add View for controller

Right click on Index() and click add View . so index.cshtml automatically will be created

In AngularJS we have used following directives

  1. ng-Click: The ngClick directive allows you to specify custom behavior when an element is clicked.
  2. ng-controller: The ngController directive attaches a controller class to the view
  3. ng-Repeat: The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.
  4. ng-model: ngModel is responsible for Binding the view into the model, which other directives such as input, textarea or select require.

Now design a table to accept inputs from user in CRUD page. Add below HTML to index.cshtml

<div ng-controller="myCntrl">
     <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

   <h1> Employee Details Page</h1>

    <br />

        <input type="button" class="btnAdd" value=" Add Employee" ng-click="AddEmployeeDiv()" />

    <div class="divList">
        <p class="divHead">Employee List</p>
        <table cellpadding="12" class="table table-bordered table-hover">
            <tr>
                <td><b>ID</b></td>
                <td><b>Name</b></td>
                <td><b>Email</b></td>
                <td><b>Age</b></td>
                <td><b>Actions</b></td>
            </tr>
            <tr ng-repeat="employee in employees">
                <td>
                    {{employee.Id}}
                </td>
                <td>
                    {{employee.name}}
                </td>
                <td>
                    {{employee.email}}
                </td>
                <td>
                    {{employee.Age}}
                </td>
                <td>
                    <span ng-click="editEmployee(employee)" class="btnAdd">Edit</span>
                    <span ng-click="deleteEmployee(employee)" class="btnRed">Delete</span>
                </td>
            </tr>
        </table>
    </div>

    <div ng-show="divEmployee">
        <p class="divHead">{{Action}} Employee</p>
        <table>
            <tr>
                <td><b>Id</b></td>
                <td>
                    <input type="text" disabled="disabled" ng-model="employeeId" />
                </td>
            </tr>
            <tr>
                <td><b>Name</b></td>
                <td>
                    <input type="text" ng-model="employeeName" />
                </td>
            </tr>
            <tr>
                <td><b>Email</b></td>
                <td>
                    <input type="text" ng-model="employeeEmail" />
                </td>
            </tr>
            <tr>
                <td><b>Age</b></td>
                <td>
                    <input type="text" ng-model="employeeAge" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="button" class="btnAdd" value="Save" ng-click="AddUpdateEmployee()" />
                </td>
            </tr>
        </table>
    </div>
</div>

Step 3: Writing AngularJS MVC code

So We are ready with our Model View and Controller now we have to write AngularJS code

Create three JavaScript files as shown in below

  1. Controller.js
  2. Module.js
  3. Service.js

1. Module.js

angular.module is used to configure the $injector. The module is a container for the different parts of an application

2. Service.js

Service.js file is used for calling server side code by using $http. In Service.js file we have created an AngularJS service called as myService. To call MVC HomeControllers insert update,delete function we have created three functions in service.js

We have created following method in service to Call Server Side Code

  1. getEmployees()
  2. updateEmp
  3. AddEmp
  4. DeleteEmp
app.service("myService", function ($http) {

    //get All Eployee
    this.getEmployees = function () {
        debugger;
        return $http.get("Home/GetAll");
    };

    // get Employee By Id
    this.getEmployee = function (employeeID) {
        var response = $http({
            method: "post",
            url: "Home/getEmployeeByNo",
            params: {
                id: JSON.stringify(employeeID)
            }
        });
        return response;
    }

    // Update Employee
    this.updateEmp = function (employee) {
        var response = $http({
            method: "post",
            url: "Home/UpdateEmployee",
            data: JSON.stringify(employee),
            dataType: "json"
        });
        return response;
    }

    // Add Employee
    this.AddEmp = function (employee) {
        var response = $http({
            method: "post",
            url: "Home/AddEmployee",
            data: JSON.stringify(employee),
            dataType: "json"
        });
        return response;
    }

    //Delete Employee
    this.DeleteEmp = function (employeeId) {
        var response = $http({
            method: "post",
            url: "Home/DeleteEmployee",
            params: {
                employeeId: JSON.stringify(employeeId)
            }
        });
        return response;
    }

3. Controller.js

In controller.js we have created new controller named myCntrl. In controller we are calling method of myService in controller.js

app.controller("myCntrl", function ($scope, myService) {
    $scope.divEmployee = false;
    GetAllEmployee();
    //To Get All Records 
    function GetAllEmployee() {
        debugger;
        var getData = myService.getEmployees();
        debugger;
        getData.then(function (emp) {
            $scope.employees = emp.data;
        },function () {
            alert('Error in getting records');
        });
    }

    $scope.editEmployee = function (employee) {
        debugger;
        var getData = myService.getEmployee(employee.Id);
        getData.then(function (emp) {
            $scope.employee = emp.data;
            $scope.employeeId = employee.Id;
            $scope.employeeName = employee.name;
            $scope.employeeEmail = employee.email;
            $scope.employeeAge = employee.Age;
            $scope.Action = "Update";
            $scope.divEmployee = true;
        },
        function () {
            alert('Error in getting records');
        });
    }

    $scope.AddUpdateEmployee = function ()
    {
        debugger;
        var Employee = {
            Name: $scope.employeeName,
            Email: $scope.employeeEmail,
            Age: $scope.employeeAge
        };
        var getAction = $scope.Action;

        if (getAction == "Update") {
            Employee.Id = $scope.employeeId;
            var getData = myService.updateEmp(Employee);
            getData.then(function (msg) {
                GetAllEmployee();
                alert(msg.data);
                $scope.divEmployee = false;
            }, function () {
                alert('Error in updating record');
            });
        } else {
            var getData = myService.AddEmp(Employee);
            getData.then(function (msg) {
                GetAllEmployee();
                alert(msg.data);
                $scope.divEmployee = false;
            }, function () {
                alert('Error in adding record');
            });
        }
    }

    $scope.AddEmployeeDiv=function()
    {
        ClearFields();
        $scope.Action = "Add";
        $scope.divEmployee = true;
    }

    $scope.deleteEmployee = function (employee)
    {
        var getData = myService.DeleteEmp(employee.Id);
        getData.then(function (msg) {
            GetAllEmployee();
            alert('Employee Deleted');
        },function(){
            alert('Error in Deleting Record');
        });
    }

    function ClearFields() {
        $scope.employeeId = "";
        $scope.employeeName = "";
        $scope.employeeEmail = "";
        $scope.employeeAge = "";
    }
});

Step 4: Call AngularJS

In the final we have to call AngularJS .We are calling AngularJS in layout.cshtml page

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />

   <title>@ViewBag.Title</title>

    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Content/Angular/Module.js"></script>
    <script src="~/Content/Angular/Service.js"></script>
    <script src="~/Content/Angular/Controller.js"></script>
    @Styles.Render("~/Content/css")
    <style>
       
    </style>
</head>
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")

    @RenderSection("scripts", required: false)
</body>
</html>

By using this, you have successfully inserted data in the database and you have also shown this in the gridview. Click on Add Employee

Please take a look at the attached code for more information. Download AngulaJsExample.zip

Happy programming!!

Don’t forget to leave your feedback and comments below!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here