Click here to Skip to main content
15,867,977 members
Articles / Web Development / HTML

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

Rate me:
Please Sign up or sign in to vote.
4.84/5 (69 votes)
7 Nov 2015CPOL4 min read 285.3K   21.1K   124   67
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.

Image 1

Select basic ASP.NET MVC 4 project template

Image 2

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

    Image 3

  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

    Image 4

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

Image 5

Add new Entity Data Model using Entity framework in Models folder

Image 6

Select Database name from dropdown

Image 7

Now We have model class for Employee .

Step 2: Create Controller in MVC project

Add new controller named as HomeController

Image 8

Add below methods to HomeController

C#
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

HTML
<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

Image 9

1. Module.js

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

Image 10

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
JavaScript
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

JavaScript
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

HTML
<!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

Image 11

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Sujit Bhujbal is Senior Software Engineer having over 12 + years of Experience in .NET core , C#, Angular , SQL Server and has worked on various platforms. He worked during various phases of SDLC such as Requirements and Analysis, Design and Construction, development, maintenance, Testing, UAT.

He is Microsoft Certified Technology Specialist (MCTS) in Asp.net /WCF Applications. He worked at various levels and currently working as a Senior Software Engineer.

His core areas of skill are Web application development using WPF,WCF , C#.Net, ASP.Net 3.5, WCF, SQL Server 2008, CSS, Java script Web design using HTML, AJAX and Crystal Reports

He is proficient in developing applications using SilverLight irrespective of the language, with sound knowledge of Microsoft Expression Blend and exposure to other Microsoft Expression studio tools.


Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

------------------------------------------------------------------------
Blog: Visit Sujit Bhujbal

CodeProject:- Sujit Bhujbal codeproject

DotNetHeaven:- DotNetHeaven

CsharpCorner:-CsharpCorner

Linkedin :-Linkedin

Stack-Exchange: <a href="http://stackexchange.com/users/469811/sujit-bhu

Comments and Discussions

 
GeneralMy vote of 5 Pin
maq_rohit28-Oct-15 12:09
professionalmaq_rohit28-Oct-15 12:09 
GeneralMy Vote 5 Pin
Sanket Bankar28-Oct-15 1:08
Sanket Bankar28-Oct-15 1:08 
GeneralRe: My Vote 5 Pin
Sujeet Bhujbal28-Oct-15 1:47
Sujeet Bhujbal28-Oct-15 1:47 
Questionnewly inserted record is not getting updated in the "Employee List" table Pin
Arjun Mourya12-Oct-15 6:46
Arjun Mourya12-Oct-15 6:46 
AnswerRe: newly inserted record is not getting updated in the "Employee List" table Pin
Sujeet Bhujbal12-Oct-15 22:49
Sujeet Bhujbal12-Oct-15 22:49 
GeneralRe: newly inserted record is not getting updated in the "Employee List" table Pin
Member 1205582713-Oct-15 6:22
Member 1205582713-Oct-15 6:22 
GeneralRe: newly inserted record is not getting updated in the "Employee List" table Pin
Arjun Mourya13-Oct-15 18:39
Arjun Mourya13-Oct-15 18:39 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun6-Oct-15 1:01
Humayun Kabir Mamun6-Oct-15 1:01 
Nice...
GeneralRe: My vote of 5 Pin
Sujeet Bhujbal6-Oct-15 19:31
Sujeet Bhujbal6-Oct-15 19:31 
SuggestionExcellent example from an implementation perspective: Missed on "What is angular.js" Pin
Member 119488551-Oct-15 7:16
Member 119488551-Oct-15 7:16 
GeneralRe: Excellent example from an implementation perspective: Missed on "What is angular.js" Pin
Sujeet Bhujbal6-Oct-15 19:30
Sujeet Bhujbal6-Oct-15 19:30 
QuestionSource Code Pin
mert atayurt30-Sep-15 1:22
mert atayurt30-Sep-15 1:22 
AnswerRe: Source Code Pin
aarif moh shaikh30-Sep-15 2:51
professionalaarif moh shaikh30-Sep-15 2:51 
GeneralRe: Source Code Pin
Gopi Kishan Mariyala30-Sep-15 3:09
Gopi Kishan Mariyala30-Sep-15 3:09 
GeneralRe: Source Code Pin
Sujeet Bhujbal30-Sep-15 3:22
Sujeet Bhujbal30-Sep-15 3:22 
GeneralRe: Source Code Pin
Gopi Kishan Mariyala30-Sep-15 20:03
Gopi Kishan Mariyala30-Sep-15 20:03 
GeneralRe: Source Code Pin
Sujeet Bhujbal30-Sep-15 3:23
Sujeet Bhujbal30-Sep-15 3:23 
GeneralRe: Source Code Pin
aarif moh shaikh30-Sep-15 18:23
professionalaarif moh shaikh30-Sep-15 18:23 
AnswerRe: Source Code Pin
Sujeet Bhujbal30-Sep-15 7:51
Sujeet Bhujbal30-Sep-15 7:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.