Click here to Skip to main content
13,250,453 members (50,878 online)
Click here to Skip to main content
Add your own
alternative version

Stats

151.2K views
15.2K downloads
112 bookmarked
Posted 30 Sep 2015

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

, 7 Nov 2015
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sujit Bhujbal
Technical Lead
India India
Sujit Bhujbal is Senior Software Engineer having over 6 + years of Experience in Asp.net 3.5,WPF,WCF 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

Personal Website :-Visit sujit Bhujbal Personal Site

Facebook :- Sujit Bhujbal Facebook

CodeProject:- Sujit Bhujbal codeproject

DotNetHeaven:- DotNetHeaven

CsharpCorner:-CsharpCorner

Linkedin :-Linkedin

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

You may also be interested in...

Comments and Discussions

 
QuestionProbelm Pin
Member 1343679613-Oct-17 21:22
memberMember 1343679613-Oct-17 21:22 
AnswerRe: Probelm Pin
Sujit Bhujbal17-Oct-17 5:08
memberSujit Bhujbal17-Oct-17 5:08 
QuestionThis article is very useful Pin
tintokthomas57727-Sep-17 23:51
membertintokthomas57727-Sep-17 23:51 
AnswerRe: This article is very useful Pin
Sujit Bhujbal17-Oct-17 5:09
memberSujit Bhujbal17-Oct-17 5:09 
QuestionI got System.Data.Entity.Infrastructure.DbUpdateException Pin
Richard P.H. Wu27-Aug-17 17:26
memberRichard P.H. Wu27-Aug-17 17:26 
QuestionRefresh Error Pin
atlanti20-Aug-17 1:17
groupatlanti20-Aug-17 1:17 
Praisevery useful article Pin
Member 1336006014-Aug-17 21:13
memberMember 1336006014-Aug-17 21:13 
QuestionThanks Pin
Member 1332661925-Jul-17 4:16
memberMember 1332661925-Jul-17 4:16 
Buggetting error while displaying records Pin
Member 1329081616-Jul-17 20:25
memberMember 1329081616-Jul-17 20:25 
QuestionData is not showing on the page Pin
Member 132908167-Jul-17 17:54
memberMember 132908167-Jul-17 17:54 
BugRe: Data is not showing on the page Pin
Member 132908167-Jul-17 17:57
memberMember 132908167-Jul-17 17:57 
Questionselect using AngularJS's ng-options Pin
wilmer123456720-Apr-17 3:46
memberwilmer123456720-Apr-17 3:46 
Questionvery helpfull Article. Pin
dvvcvcxv23-Mar-17 2:12
memberdvvcvcxv23-Mar-17 2:12 
BugError Pin
Member 1304800614-Mar-17 3:29
memberMember 1304800614-Mar-17 3:29 
GeneralRe: Error Pin
Sujit Bhujbal16-Mar-17 21:14
memberSujit Bhujbal16-Mar-17 21:14 
QuestionAngular does not allow duplicated value Pin
teavdara19-Jun-16 0:22
memberteavdara19-Jun-16 0:22 
AnswerRe: Angular does not allow duplicated value Pin
Sujit Bhujbal7-Jul-16 2:55
memberSujit Bhujbal7-Jul-16 2:55 
Questionwhat is the "debugger" ? where it's definition ? Pin
a1_shay28-May-16 1:27
membera1_shay28-May-16 1:27 
AnswerRe: what is the "debugger" ? where it's definition ? Pin
Sujit Bhujbal7-Jul-16 2:55
memberSujit Bhujbal7-Jul-16 2:55 
GeneralExcellent Post for learners Pin
Satya Narayana9-Feb-16 1:05
memberSatya Narayana9-Feb-16 1:05 
GeneralRe: Excellent Post for learners Pin
Sujit Bhujbal8-Mar-16 0:34
memberSujit Bhujbal8-Mar-16 0:34 
GeneralFollowing the instructions came-up with different project compared to downloadable project. Pin
Member 123151528-Feb-16 22:34
memberMember 123151528-Feb-16 22:34 
SuggestionInclude code to fix problem for IE's UI not refresh after insert, update , delete Pin
Johnson TONG Aussie6-Feb-16 20:26
memberJohnson TONG Aussie6-Feb-16 20:26 
GeneralRe: Include code to fix problem for IE's UI not refresh after insert, update , delete Pin
Sujit Bhujbal8-Mar-16 0:31
memberSujit Bhujbal8-Mar-16 0:31 
NewsEdit, Delete, Insert all Update UI in all browsers except IE Pin
Member 18549366-Feb-16 17:15
memberMember 18549366-Feb-16 17:15 
GeneralRe: Edit, Delete, Insert all Update UI in all browsers except IE Pin
Sujit Bhujbal8-Mar-16 0:33
memberSujit Bhujbal8-Mar-16 0:33 
Questiongreat tutorial!!! Pin
Member 1123601823-Jan-16 19:40
memberMember 1123601823-Jan-16 19:40 
AnswerRe: great tutorial!!! Pin
Sujit Bhujbal27-Jan-16 20:25
memberSujit Bhujbal27-Jan-16 20:25 
QuestionIssue Pin
Member 1042853811-Dec-15 0:13
memberMember 1042853811-Dec-15 0:13 
AnswerRe: Issue Pin
Sujit Bhujbal16-Dec-15 2:20
memberSujit Bhujbal16-Dec-15 2:20 
QuestionThanks Pin
NhrTech30-Nov-15 20:37
memberNhrTech30-Nov-15 20:37 
AnswerRe: Thanks Pin
Sujit Bhujbal8-Dec-15 20:39
memberSujit Bhujbal8-Dec-15 20:39 
Questioncontroller or directive Pin
pvigori12-Nov-15 5:24
memberpvigori12-Nov-15 5:24 
AnswerRe: controller or directive Pin
Sujit Bhujbal16-Nov-15 1:14
memberSujit Bhujbal16-Nov-15 1:14 
GeneralRe: controller or directive Pin
pvigori16-Nov-15 2:15
memberpvigori16-Nov-15 2:15 
GeneralRe: controller or directive Pin
Sujit Bhujbal16-Nov-15 19:33
memberSujit Bhujbal16-Nov-15 19:33 
QuestionDelete Record Error Pin
Lee NeeHau2-Nov-15 15:14
memberLee NeeHau2-Nov-15 15:14 
AnswerRe: Delete Record Error Pin
Sujit Bhujbal5-Nov-15 18:43
memberSujit Bhujbal5-Nov-15 18:43 
GeneralMy vote of 5 Pin
maq_rohit28-Oct-15 13:09
professionalmaq_rohit28-Oct-15 13:09 
GeneralMy Vote 5 Pin
Sanket Bankar28-Oct-15 2:08
memberSanket Bankar28-Oct-15 2:08 
GeneralRe: My Vote 5 Pin
Sujit Bhujbal28-Oct-15 2:47
memberSujit Bhujbal28-Oct-15 2:47 
Questionnewly inserted record is not getting updated in the "Employee List" table Pin
Arjun Mourya12-Oct-15 7:46
memberArjun Mourya12-Oct-15 7:46 
AnswerRe: newly inserted record is not getting updated in the "Employee List" table Pin
Sujit Bhujbal12-Oct-15 23:49
memberSujit Bhujbal12-Oct-15 23:49 
GeneralRe: newly inserted record is not getting updated in the "Employee List" table Pin
Member 1205582713-Oct-15 7:22
memberMember 1205582713-Oct-15 7:22 
GeneralRe: newly inserted record is not getting updated in the "Employee List" table Pin
Arjun Mourya13-Oct-15 19:39
memberArjun Mourya13-Oct-15 19:39 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun6-Oct-15 2:01
memberHumayun Kabir Mamun6-Oct-15 2:01 
GeneralRe: My vote of 5 Pin
Sujit Bhujbal6-Oct-15 20:31
memberSujit Bhujbal6-Oct-15 20:31 
SuggestionExcellent example from an implementation perspective: Missed on "What is angular.js" Pin
Member 119488551-Oct-15 8:16
memberMember 119488551-Oct-15 8:16 
GeneralRe: Excellent example from an implementation perspective: Missed on "What is angular.js" Pin
Sujit Bhujbal6-Oct-15 20:30
memberSujit Bhujbal6-Oct-15 20:30 
QuestionSource Code Pin
mert atayurt30-Sep-15 2:22
membermert atayurt30-Sep-15 2:22 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 8 Nov 2015
Article Copyright 2015 by Sujit Bhujbal
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid