AngularJS CRUD Using ASP.NET MVC5 – VS 2015 Project Setup and Read Employee Data


In this article, we will learn how to perform CRUD (Create, Read, Update and Delete) operation using AngularJS and ASP.NET MVC5.

We will use single table for CRUD operation to make things simple and understandable. Our aim is to learn the concept of AngularJS.

I am planning to divide this article in four parts.

During this journey, we will learn angular CRUD operation, angular validations and angular notifications.

Following tools and technologies will be used in this article.

  • Visual Studio 2015 Community Edition
  • ASP.NET MVC 5
  • .Net Framework 4.5.2
  • Entity Framework 5.0 (ADO.NET Entity Data Model)
  • AngularJS 1.6.4
  • Bootstrap for Page Designing

Step-1: Create MVC Project.

Let’s create a new MVC Application by opening Visual Studio. I am using VS 2015 community edition for this article. You can use any edition like VS 2013/2015/2017.

File –> New –> Project –> Select ASP.NET Web Application and give name.

step-1-create-project

Click on OK will open a new window, select MVC template.

Step-2-select-mvc-template

Click on Change Authentication, will open a popup,  select No Authentication and click on OK, OK will close the windows and will create a new MVC 5.0 project template.

step-3-select-no-auth

In Solution Explorer window, we can see the structure of our project.

step-4-project-structure

Step-2: Create Model classes for existing DB tables using ADO.NET Entity Data Model

For this article, we are going to use my existing Employee table. you can create this table using below SQL script:


CREATE TABLE [dbo].[Employee](
	[EmpID] [int] IDENTITY(1,1) NOT NULL,
	[EmpName] [nvarchar](100) NULL,
	[DeptName] [nvarchar](50) NULL,
	[Designation] [nvarchar](50) NULL,
	[Email] [nvarchar](100) NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
 [EmpID] ASC
)
WITH
(
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY]

GO

We will use Entity Framework Database-First approach, so we are going to add ADO.Net Entity Data Model in our project.

For this, right click on Models folder, Select Add and click on New Item option. Select Data Tab, Select ADO.NET Entity Data Model and give Name of Model LearningDB then press Add button.

step-5-adonet-entity-data-model

We are going to use Entity Framework Database-First Approach for this demo code so select EF Designer from database option.

Next, we will follow Entity Data Model Wizard steps to configure our Data Model.

step-6-select-db-first-option

Next screen will ask to choose your database connection. select you existing database connection if any, or create new using New Connection button.

step-7-newdbconnection

I am using SQL Express 2014 for this demo. I have filled necessary details highlighted in blue box. once all filled up, verify the connection.

step-8-selectdbconnection

Give name for connection settings in web.config as LearningDBEntities then press next.

step-9-selectEFversion

Next, we will select our Database objects for which we are going to create Data Models.

step-10-select-tables

In our case, we will only select Employee table. but we can select all the tables, views, stored procedures and functions as per our project requirement.

You can update or specify Model namespace in case any specific namespace you want to follow in your project. In our case by default it shows LearningDBModel so we will go ahead with the same.

Click on finish. Now it will generate all the necessary model , DB context classes , entity framework templates for our Data Model.

Once generated, you can see Models folder will contain all these files like Data Model class for Employee, LearningDB Context templates (files with .tt extension are template files) etc…

step-11-model-created

Web.config will also get updated with connection string for Database and other Entity Framework settings. Now we are ready to use this Entity framework data model in our project.

Next, let us install AngularJS.Core package for AngularJS.

Step-3: Install AngularJS package

Right click on project and select Manage NuGet Packages option. It will open NuGet Package manager.

Then select Browse Tab, enter search text AngularJS. select AngularJS.Core from the package list and Press Install button.

step-12-install-angularJS-package

After installation finish, Scripts folder will be updated with new AngularJS script files.

Next, let us create MVC controller.

Step-4: Create EmployeeController class to perform CRUD operation 

Select Controllers folder, right click on it and select Add then select Controller. It will open Add Scaffold window. you can select MVC 5 Controller – Empty template.

step-13-add-controller

Press Add button and then give controller a name EmployeeController. Now add the following code to fetch the Employee list from database in controller.

 public class EmployeeController : Controller
 {
    // GET Employee/GetEmployee
    public JsonResult GetEmployee()
    {
       using (LearningDBEntities db = new LearningDBEntities())
       {
         List<Employee> empList = db.Employees.ToList();
         return Json(empList, JsonRequestBehavior.AllowGet);
       }
    }
 }

Above code uses LearningDBEntities DB Context class to fetch employee data. First, we fetch employees from database and assign to List object empList. Later, we convert empList into JSON format.

Next, we will write AngularJS code to display employee data on grid format.

Step-5: Create AngularJS Module, Controller and Service for fetching Employee data.

Create new folder AngularJSApp at project level. Add Sub folder Employee under it.

Add three JavaScript files: Module.js, Controller.js and Service.js in that folder.

step-14-add-js-files

First, create module in AngularJS by opening Module.js file.

A module in AngularJS is a collection of controllers, services, directives, etc. The angular.module() function call is used to create, register, and retrieve modules in AngularJS. All modules, including those shipped by the AngularJS team and third party libraries, should be registered using the angular.module() function.

var myapp;
(function () {
    myapp = angular.module('my-employees', []);
})();

Module.js contain code to create angular module ‘my-employees‘. we will use this module ‘my-employees‘ to perform all CRUD operations using ng-app tag on view page.

Second,  create controller for our module by opening Controller.js file.

Controllers in AngularJS are the first point of entry for your code. The <module name>.controller() function call is used to create and register controllers in AngularJS. The ng-controller directive is used to represent an AngularJS controller on the HTML page. The role of the controller in Angular is to set state and behavior of the data model ($scope). Controllers should not be used to manipulate the DOM directly.

//employee controller
myapp.controller('employee-controller', function ($scope, employeeService) {

    //Loads all Employee records when page loads
    loadEmployees();

    function loadEmployees() {
        var EmployeeRecords = employeeService.getAllEmployees();
        EmployeeRecords.then(function (d) {
            //success
            $scope.Employees = d.data;
        },
        function () {
            alert("Error occured while fetching employee list...");
        });
    }
});

Controller.js file contain code to add ‘employee-controller‘  angular controller in ‘my-employees‘ angular module.

Third, create angular service by opening Service.js file.

Services in AngularJS are commonly used for shared code that is abstracted away into a file which can be used throughout the lifetime of an Angular application. Services are lazily instantiated, meaning that there will not be an instance of a service unless a component that depends on the service gets used.

//Service to get data from employee mvc controller
myapp.service('employeeService', function ($http) {

    this.getAllEmployees = function () {

        return $http.get("/Employee/GetEmployee");
    }
});

In above code, we created angular service ‘employeeService‘ which will fetch data using $http.get() method from our MVC controller. Data will be in JSON format. This service is used by our angular controller ‘employee-controller‘ to fetch employee data.

Next, we will create view by using which we will display employee data.

Step-6: Create View for displaying Employee data 

We are going to modify Views –> Home –> Index.cshtml to display Employee data in grid format.

Let us remove all the code from Index.cshtml first and then add following code:

<div class="container" ng-controller="employee-controller">
<div class="panel panel-info">
<div class="panel-heading">
            Employee Details - Grid CRUD operations</div>
<table class="table table-bordered">
<thead style="background-color:lightblue;">
<tr>
<th> Employee ID</th>
<th> Employee Name</th>
<th>Email</th>
<th>Department Name</th>
<th>Designation</th>
<th> Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in Employees">
<td> {{emp.EmpID}}</td>
<td> {{emp.EmpName}}</td>
<td>{{emp.Email}}</td>
<td>{{emp.DeptName}}</td>
<td>{{emp.Designation}}</td>
<td style="width:200px;">
    <a href="#" class="btn btn-info">Update</a>
    <a href="#" class="btn btn-danger">Delete</a></td>
</tr>
</tbody>
</table>
</div>
</div>
@section scripts{
 <script src="~/AngularJSApp/Employee/Module.js"></script>
 <script src="~/AngularJSApp/Employee/Service.js"></script>
 <script src="~/AngularJSApp/Employee/Controller.js"></script>
}

Above html code contain ng-controller=”employee-controller” using which we are going to fetch all employee data. As soon as Controller.js file load in DOM it will call  loadEmployees(); method. This method fetch the data from employeeService and assign it to $scope.Employees. This scope variable Employees is used during ng-repeat processing.

Repeating in AngularJS is done via a primitive directive called ng-repeat. The ng-repeat directive repeats a given HTML element in a view over the length of a repeating data array. Repeaters in AngularJS can repeat over an array of strings or objects.

ng-repeat uses angular expressions  i.e {{emp.EmpName}} to bind data to HTML.

Expressions in AngularJS are JavaScript-like code snippets that are written inside the {{ expression }} syntax. The data from these expressions is bound to HTML the same way as ng-bind directives. The main difference between AngularJS expressions and regular JavaScript expressions is that AngularJS expressions are evaluated against the $scope object in AngularJS.

Then we added script references on this Index.cshtml for Module.js, Service.js and Controller.js.

Next, let us configure angular application to join the different dots for application to run successfully.

Step-7: Configuration of ng-app and bundle angular script files on layout page

Open Views –> Shared –> _Layout.cshtml file update body tag :

<body ng-app="my-employees">

on same page add angular Script.Render bundle

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

Open App_Start –> BundleConfig.cs file and add bundle for angular.

 bundles.Add(new ScriptBundle("~/bundles/angular").Include(
     "~/Scripts/angular.js"));

That’s it. All set.

Run the application now.

step-15-display-emplist

You can see all the employee data on beautiful grid format. Bootstrap helped us to beatify the page design.

In next article, we will add functionality for CREATE, UPDATE and DELETE Employee data using AngularJS. So stay tuned 🙂

I hope this article will help you learning AngularJS.

Please feel free to provide your feedback and comments.

Code for this article is available on GitHub:

My Learning Reference for AngularJS

Advertisements

2 thoughts on “AngularJS CRUD Using ASP.NET MVC5 – VS 2015 Project Setup and Read Employee Data

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s