Click here to Skip to main content
15,879,535 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 286K   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

 
GeneralNice article with example Pin
rajkumar992321-Jan-20 5:37
rajkumar992321-Jan-20 5:37 
QuestionGood one example Pin
Member 1405545026-Nov-18 19:47
Member 1405545026-Nov-18 19:47 
SuggestionScroll to input Pin
Gluups6-Nov-18 5:33
Gluups6-Nov-18 5:33 
GeneralUseful project Pin
Gluups5-Nov-18 22:43
Gluups5-Nov-18 22:43 
PraiseGood One Example Pin
Member 1189047030-Jul-18 23:12
Member 1189047030-Jul-18 23:12 
GeneralRe: Good One Example Pin
Member 1405545021-Nov-18 22:22
Member 1405545021-Nov-18 22:22 
QuestionWrong Database Table Script Pin
Member 115103323-Feb-18 0:48
Member 115103323-Feb-18 0:48 
AnswerRe: Wrong Database Table Script Pin
Sujeet Bhujbal3-Apr-18 0:11
Sujeet Bhujbal3-Apr-18 0:11 
QuestionProbelm Pin
Member 1343679613-Oct-17 20:22
Member 1343679613-Oct-17 20:22 
AnswerRe: Probelm Pin
Sujeet Bhujbal17-Oct-17 4:08
Sujeet Bhujbal17-Oct-17 4:08 
QuestionThis article is very useful Pin
tintokthomas57727-Sep-17 22:51
tintokthomas57727-Sep-17 22:51 
AnswerRe: This article is very useful Pin
Sujeet Bhujbal17-Oct-17 4:09
Sujeet Bhujbal17-Oct-17 4:09 
QuestionI got System.Data.Entity.Infrastructure.DbUpdateException Pin
Richard P.H. Wu27-Aug-17 16:26
Richard P.H. Wu27-Aug-17 16:26 
QuestionRefresh Error Pin
atlanti20-Aug-17 0:17
atlanti20-Aug-17 0:17 
Praisevery useful article Pin
Member 1336006014-Aug-17 20:13
Member 1336006014-Aug-17 20:13 
QuestionThanks Pin
Member 1332661925-Jul-17 3:16
Member 1332661925-Jul-17 3:16 
Buggetting error while displaying records Pin
Member 1329081616-Jul-17 19:25
Member 1329081616-Jul-17 19:25 
QuestionData is not showing on the page Pin
Member 132908167-Jul-17 16:54
Member 132908167-Jul-17 16:54 
BugRe: Data is not showing on the page Pin
Member 132908167-Jul-17 16:57
Member 132908167-Jul-17 16:57 
Questionselect using AngularJS's ng-options Pin
wilmerandrade20-Apr-17 2:46
wilmerandrade20-Apr-17 2:46 
Questionvery helpfull Article. Pin
dvvcvcxv23-Mar-17 1:12
dvvcvcxv23-Mar-17 1:12 
BugError Pin
Member 1304800614-Mar-17 2:29
Member 1304800614-Mar-17 2:29 
When i click on addEmployee and enter the value after that i click on save the value then they show me error

error is:
Error in Adding record
prevent this page from creating additional dialogs

and one more thing you database is different and you have written different code in cshtml file.
GeneralRe: Error Pin
Sujeet Bhujbal16-Mar-17 20:14
Sujeet Bhujbal16-Mar-17 20:14 
QuestionAngular does not allow duplicated value Pin
teavdara18-Jun-16 23:22
teavdara18-Jun-16 23:22 
AnswerRe: Angular does not allow duplicated value Pin
Sujeet Bhujbal7-Jul-16 1:55
Sujeet Bhujbal7-Jul-16 1:55 

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.