AngularJS CRUD Using ASP.NET MVC5 – Add Toaster Notifications

In Previous article we learn how to add form data validations for CREATE and UPDATE Operation. In this article, we will learn how to add toaster notifications in our application.

You can download code for previous article from GitHub and start adding code for toaster notification.

So Let us start coding ??

Step-1: Download “toaster.css“, “toaster.js” and “angular-animate.min.js

Note: we need to also update angular.js version to AngularJS v1.5.6, because latest version v1.6.4 is not working with toaster.js and we need to downgrade to make toaster works with angularJS.

Now all set. dependencies are set in the project.

Step-2: Bundle this JS and CSS files in our project

Open “App_Start –> BundleConfig.cs” file and update the angular bundle


bundles.Add(new ScriptBundle("~/bundles/angular").Include(
                       "~/Scripts/angular.js",
                       "~/Scripts/angular-animate.min.js",
                       "~/Scripts/toaster.js"));

Similarly css bundle:


bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css",
                      "~/Content/toaster.css"));

Step-3: Include the ‘ngAnimate‘ and ‘toaster‘ module in your AngularJS app

Open “AngularJSApp\Employee\Module.js” file and add module like

myapp = angular.module('my-employees', ['toaster', 'ngAnimate', 'ui.bootstrap.showErrors']);

Note: ngAnimate module require if you want animations during toaster notification.

Step-4: Add ‘toaster-container‘ directive in Index.cshtml

By default, toasts have a timeout setting of 5000, meaning that they are removed after 5000 milliseconds. If the timeout is set to 0, the toast will be considered “sticky” and will not automatically dismiss. The timeout can be configured at three different levels:

Globally in the config for all toast types:

<toaster-container toaster-options="{'time-out': 1000}">
</toaster-container>

Per info-class type: By passing the time-out configuration as an object instead of a number, you can specify the global behavior an info-class type should have.

<toaster-container
toaster-options="{'time-out':{ 'toast-success': 2000, 'toast-error': 0 } }">
</toaster-container>

We will add following toaster-options for our toasts to display.

<toaster-container
toaster-options="{'close-button':true, 'time-out':{ 'toast-success': 2000, 'toast-error': 0 } }">
</toaster-container>

Success toasts will fade out after 2 seconds and error toasts will be sticky, until you close it. we also used close-button property which will show close button for all our toasts, so user can manually close our error toasts using close button.

Step-5: Usage of toaster in ng-controller

Let us update our JavaScript alert messages for success and failure for ‘employee-controller‘ in “AngularJSApp –> Employee –> Controller.js” by adding toaster notifications.

First, inject toaster module in our controller:

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

Then, you can use it any where in our controller.

For Success :

toaster.success({ title: "Success", body: "Employee added successfully" });

For error :

toaster.error("Error", "Error occured while loading employee data");

Similarly, you can update all other javascript alerts will toaster notifications for UPDATE and DELETE methods.

Step-6: Run the application.

Click on Add Employee Button. Provide input values in each fields and save the data.

Success-Added

You can see that it will give smooth effective notifications for success and it will fade out after 2 seconds.

Kool 🙂 Isn’t it?

Update Employee

Success-Updated

Delete Employee

Success-Deleted

Code for this article is available on GitHub: https://github.com/sandy060583/AngularJSUsingMVC5-Part4

For more details on toaster, please refer this article: https://github.com/jirikavi/AngularJS-Toaster

That’s all for this article.

Please feel free to provide your feedback and comments.

AngularJS CRUD Using ASP.NET MVC5 – Data Validations during CREATE and UPDATE Operation

In Previous article we learn how to CREATE, UPDATE and DELETE Employee data using AngularJS. In this article, we will learn how AngularJS and Bootstrap help us to effectively do form validation.

You can download code for previous article from GitHub and start adding code for form data validation.

So Let us start coding ??

We will use custom directive created by “Paul Yoder” to do Form Validation. It is effective and has all the functionality we are looking for.

You can use any other directive available for form validation as per your need.

Step-1: Download showErrors.js from GitHub

Source Path: https://raw.githubusercontent.com/paulyoder/angular-bootstrap-show-errors/master/src/showErrors.min.js

Add this JS file in our project “Scripts” folder.

Step-2: Add Script Reference on Page

We need to add reference of “showErrors.min.js” JavaScript file on “Views –> Home –> Index.cshtml” page’s script section.

@section scripts{
<script src="~/AngularJSApp/Employee/Module.js"></script>
<script src="~/Scripts/showErrors.min.js"></script>
<script src="~/AngularJSApp/Employee/Service.js"></script>
<script src="~/AngularJSApp/Employee/Controller.js"></script>
}

Order of JS file is important here. Make sure you add it after Module.JS and Before Controller.JS file where this directive will be used for form validation purpose.

Step-3: Include the “ui.bootstrap.showErrors” module in your Angular app

Open “AngularJSApp\Employee\Module.js” file and add this module:

myapp = angular.module('my-employees', ['ui.bootstrap.showErrors']);

Step-4: Add the “show-errors” attribute on the div element that contains the “form-group” class

Open “Index.cshtml” page and add angular validation for our directives as per below for “AddNewForm” and “UpdateEmployeeForm“. we only need to change form-group divs where our input controls are placed.

If you only want to show valid values on specific inputs, then you can pass in the { showSuccess: true } option.

<div class="form-group" show-errors="{ showSuccess: true }">
  <label class="control-label"> Employee Name</label>
  <input class="form-control" name="EmpName" ng-model="EmpName" type="text"
placeholder="Employee Name" ng-required="true" /></div>

Similarly, other form-control will be updated for “AddNewForm” form:

<form class="form-horizontal" name="AddNewForm">
<div class="form-group">
   <input class="form-control" readonly="readonly" name="EmpNo"
ng-model="EmpNo" type="hidden" placeholder="Employee Number" /></div>
<div class="form-group" show-errors="{ showSuccess: true }">
    <label class="control-label"> Employee Name</label>
    <input class="form-control" name="EmpName" ng-model="EmpName"
type="text" placeholder="Employee Name" ng-required="true" /></div>
<div class="form-group" show-errors="{ showSuccess: true }">
  <label class="control-label"> Email</label>
  <input class="form-control" name="Email" ng-model="Email" type="email"
placeholder="Email" ng-required="true" /></div>
<div class="form-group" show-errors="{ showSuccess: true }">
   <label class="control-label"> Department Name</label>
   <input class="form-control" name="DeptName" ng-model="DeptName"
type="text" placeholder="Dept Name" ng-required="true" /></div>
<div class="form-group" show-errors="{ showSuccess: true }">
   <label class="control-label"> Designation</label>
   <input class="form-control" name="Designation" ng-model="Designation"
type="text" placeholder="Designation" ng-required="true" /></div>
</form>

Submit button should not contain data-dismiss=”modal” attributes. Remove it to make modal popup open even after Submit click in case any data is invalid.

Similarly, other form-control will be updated for “UpdateEmployeeForm” form:

<form class="form-horizontal" name="UpdateEmployeeForm">
<div class="form-group">
   <input class="form-control" readonly="readonly" name="EmpNo"
ng-model="UpdateEmpNo" type="hidden" placeholder="Employee Number" /></div>
<div class="form-group" show-errors="{ showSuccess: true }">
   <label class="text-info"> Employee Name</label>
  <input class="form-control" name="EmpName" ng-model="UpdateEmpName"
type="text" placeholder="Employee Name" ng-required="true" /></div>
<div class="form-group" show-errors="{ showSuccess: true }">
     <label class="text-info"> Email</label>
     <input class="form-control" name="Email" ng-model="UpdateEmail"
type="email" placeholder="Email" ng-required="true" /></div>
<div class="form-group" show-errors="{ showSuccess: true }">
   <label class="text-info"> Department Name</label>
   <input class="form-control" name="DeptName" ng-model="UpdateDeptName"
type="text" placeholder="Dept Name" ng-required="true"/></div>
<div class="form-group" show-errors="{ showSuccess: true }">
   <label class="text-info"> Designation</label>
   <input class="form-control" name="Designation"
ng-model="UpdateDesignation" type="text" placeholder="Designation"
ng-required="true" /></div>
</form>

Step-5: Force Validity Check on form elements

By default this directive doesn’t check the validity until the user tabs off the input element. However, there are times you want to show invalid form elements even if the user has not tabbed off. To force the validity check, broadcast the show-errors-check-validity event.

Open “AngularJSApp\Employee\Controller.js” file.

In $scope.save() method, we need to broadcast this event and if form is valid then only proceed for saving data else show error message and restrict user to save invalid data.


$scope.save = function () {

  $scope.$broadcast('show-errors-check-validity');
  if ($scope.AddNewForm.$invalid)
  {
   return;
  }

  ....
  ....
}

Similarly, for $scope.update() method:


$scope.update = function () {

  $scope.$broadcast('show-errors-check-validity');

  if ($scope.UpdateEmployeeForm.$invalid)
  {
     return;
  }
 ....
 ....
}

Step-6: Reset form elements

You can broadcast the ‘show-errors-reset‘ event to remove any errors on the form elements.

we have two reset methods ($scope.resetUpdate() method and $scope.resetSave()) where will add this event.


$scope.$broadcast('show-errors-reset');

Note: There are also other useful validation attributes are available with this directive (showErrors.js), you can go to GitHub reference page and explore/use them as per your requirements.

Step-7: Run the application.

Click on Add Employee Button. Provide input values in each fields and check required field validation and email validation is working or not by keeping them empty and giving incorrect values in text-box.

add-form-validation

You can see that it will give smooth effective data validation where color of textbox fields are changing to Green or Red as per validation pass or fail.

Kool 🙂 Isn’t it?

Similarly, try Update Employee

update-form-validation

I hope this will help you in your project for doing effective data validation by minimum efforts.

For more details on AngularJS form Validation, please refer this article: https://scotch.io/tutorials/angularjs-form-validation

Code for this article is available on GitHub: https://github.com/sandy060583/AngularJSUsingMVC5-Part3

Custom Directive Used: https://github.com/paulyoder/angular-bootstrap-show-errors

That’s all for this article. In next article we will integrate “toaster” notifications in our code. Till than stay tuned 🙂

Please feel free to provide your feedback and comments.

AngularJS CRUD Using ASP.NET MVC5 – CREATE, UPDATE and DELETE Employee Data

In Previous article we setup Visual Studio 2015 project for AngularJS  and performed read operation on Employee Table. In this article, we will see how to CREATE, UPDATE and DELETE Employee  data.

You can download code for previous article from GitHub and start adding code for CREATE, UPDATE and DELETE Employee data.

So Let us start coding 🙂

Step-1: CREATE Operation – Add new employee data

First, we need to add new method Insert in EmployeeController which will add employee entity into SQL database. So Let us add following code in Controllers –> EmployeeController.cs:

//POST Employee/AddEmployee
[HttpPost]
public JsonResult Insert(Employee employee)
{
    if (employee != null)
    {
        using (LearningDBEntities db = new LearningDBEntities())
        {
            db.Employees.Add(employee);
            db.SaveChanges();
            return Json(new { success = true });
        }
    }
    else
    {
        return Json(new { success = false });
    }
}

Above code will Insert employee details into database, which is returning a JSON result of boolean data type. If it’s true then it indicate that data inserted to database successfully.

Second, we need to add following code in AngularJSApp–> Employee–> Service.js file which call MVC EmployeeController’s Insert method using $http.post method:

//add new employee
this.save = function (Employee) {
    var request = $http({
        method: 'post',
        url: '/Employee/Insert',
        data: Employee
    });
    return request;
}

Third, we need to add following code in AngularJSApp–> Employee–> Controller.js file which will call angular employeeService –> save method. once save is successful we are resetting $scope objects and reloading employee data to display new record in list.

//save employee data
$scope.save = function () {
    var Employee = {
        EmpNo: $scope.EmpNo,
        EmpName: $scope.EmpName,
        Email: $scope.Email,
        DeptName: $scope.DeptName,
        Designation: $scope.Designation
    };
    var saverecords = employeeService.save(Employee);
    saverecords.then(function (d) {
        if (d.data.success === true) {
            loadEmployees();
            alert("Employee added successfully");
            $scope.resetSave();
        }
        else { alert("Employee not added."); }
    },
    function () {
        alert("Error occurred while adding employee.");
    });
}
//reset controls after save operation
$scope.resetSave = function () {
    $scope.EmpNo = '';
    $scope.EmpName = '';
    $scope.Email = '';
    $scope.DeptName = '';
    $scope.Designation = '';
}

Finally, we need to add following html code in Views–> Home–> Index.cshtml file which will help us to submit form data using ng-controller and ng-model binding and later on this $scope object values will be used by $scope.save method to save the data:

@*New record Modal addition..*@
<div class="modal" id="AddNew" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
     <button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="text-info">Add New Employee</h3>
</div>
<div class="modal-body" style="margin-left:20px">
   @*Add New Employee form starts here...*@
<form class="form-horizontal" name="AddNewForm" >
<div class="form-group">
   <input class="form-control" readonly="readonly"
name="EmpNo" ng-model="EmpNo" type="hidden"
placeholder="Employee Number" /></div>
<div class="form-group">
<label class="control-label"> Employee Name</label>
   <input class="form-control" name="EmpName"
ng-model="EmpName" type="text"
placeholder="Employee Name" /></div>
<div class="form-group">
   <label class="control-label"> Email</label>
   <input class="form-control" name="Email"
ng-model="Email" type="email" placeholder="Email" /></div>
<div class="form-group">
    <label class="control-label"> Department Name</label>
    <input class="form-control" name="DeptName"
ng-model="DeptName" type="text"
placeholder="Dept Name" /></div>
<div class="form-group">
   <label class="control-label"> Designation</label>
   <input class="form-control" name="Designation"
ng-model="Designation" type="text"
placeholder="Designation" /></div>
</form></div>
<div class="modal-footer">
   <button type="button" class="btn btn-primary"
id="btnSave" data-dismiss="modal" ng-click="save()">Save</button>
   <button type="button" class="btn btn-default"
data-dismiss="modal" ng-click="resetSave()">Close</button></div>
</div>
</div>
</div>

Next, let us add code for update operation.

Step-2: UPDATE Operation – Update existing employee data

First, we need to add new method Update  in EmployeeController which will update employee entity into SQL database. So Let us add following code in Controllers –> EmployeeController.cs:

//POST Employee/Update
[HttpPost]
public JsonResult Update(Employee updatedEmployee)
{
    using (LearningDBEntities db = new LearningDBEntities())
    {
        Employee existingEmployee = db.Employees.Find(updatedEmployee.EmpID);
        if (existingEmployee == null)
        {
            return Json(new { success = false });
        }
        else
        {
            existingEmployee.EmpName = updatedEmployee.EmpName;
            existingEmployee.DeptName = updatedEmployee.DeptName;
            existingEmployee.Email = updatedEmployee.Email;
            existingEmployee.Designation = updatedEmployee.Designation;
            db.SaveChanges();
            return Json(new { success = true });
        }
    }
}

Above code will update existing employee details in database that is selected to update, which is also returning a JSON result of boolean data type. As previously If it’s true then it indicate that data updated to database successfully.

Second, we need to add following code in AngularJSApp–> Employee–> Service.js file which call MVC EmployeeController’s Update method using angular $http.post:

//update Employee records
this.update = function (Employee) {
    var updaterequest = $http({
        method: 'post',
        url: '/Employee/Update',
        data: Employee
    });
    return updaterequest;
}

Third, we need to add following code in AngularJSApp–> Employee–> Controller.js file which will call angular employeeService->update method. once data updated successfully we are resetting $scope objects and reloading employee data to display updated record in list.

//update Employee data
$scope.update = function () {
    var Employee = {
        EmpID: $scope.UpdateEmpNo,
        EmpName: $scope.UpdateEmpName,
        Email: $scope.UpdateEmail,
        DeptName: $scope.UpdateDeptName,
        Designation: $scope.UpdateDesignation
    };
    var updaterecords = employeeService.update(Employee);
    updaterecords.then(function (d) {
        if (d.data.success === true) {
            loadEmployees();
            alert("Employee updated successfully");
            $scope.resetUpdate();
        }
        else {
            alert("Employee not updated.");
        }
    },
    function () {
        alert("Error occured while updating employee record");
    });
}
//reset controls after update
$scope.resetUpdate = function () {
    $scope.UpdateEmpNo = '';
    $scope.UpdateEmpName = '';
    $scope.UpdateEmail = '';
    $scope.UpdateDeptName = '';
    $scope.UpdateDesignation = '';
}

Finally, we need to add following html code in Views–> Home–> Index.cshtml file which will help us to submit form data using ng-controller and ng-model binding and later on this $scope object values will be used by $scope.update method to update the employee data:

@*Upadate Employee records*@
<div class="modal" id="Update" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
  <button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="text-info">Update Existing Employee</h3>
</div>
<div class="modal-body" style="margin-left:20px">
 @*Update Employee form starts here...*@
<form class="form-horizontal" name="UpdateEmployeeForm">
<div class="form-group">
  <input class="form-control" readonly="readonly" name="EmpNo"
ng-model="UpdateEmpNo" type="hidden" placeholder="Employee Number" /></div>
<div class="form-group">
  <label class="text-info"> Employee Name</label>
  <input class="form-control" name="EmpName" ng-model="UpdateEmpName"
type="text" placeholder="Employee Name" /></div>
<div class="form-group">
  <label class="text-info"> Email</label>
  <input class="form-control" name="Email" ng-model="UpdateEmail"
type="email" placeholder="Email" /></div>
<div class="form-group">
  <label class="text-info"> Department Name</label>
  <input class="form-control" name="DeptName" ng-model="UpdateDeptName"
type="text" placeholder="Dept Name" /></div>
<div class="form-group">
  <label class="text-info"> Designation</label>
  <input class="form-control" name="Designation"
ng-model="UpdateDesignation" type="text"
placeholder="Designation" /></div>
</form></div>
<div class="modal-footer">
  <button type="button" class="btn btn-primary" id="btnUpdate"
data-dismiss="modal" ng-click="update()">
     Update
   </button>
   <button type="button" class="btn btn-default"
data-dismiss="modal">Close</button></div>
</div>
</div>
</div>

Next, let us add code for delete operation.

Step-3: DELETE Operation – Delete employee data

First, we need to add new method Delete in EmployeeController which will Delete employee entity. So Let us add following code in Controllers –> EmployeeController.cs:

//POST Employee/Delete/1
[HttpPost]
public JsonResult Delete(int id)
{
    using (LearningDBEntities db = new LearningDBEntities())
    {
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return Json(new { success = false });
        }
        db.Employees.Remove(employee);
        db.SaveChanges();
        return Json(new { success = true });
    }
}

Above code will delete existing employee details from database that is selected to delete, which is also returning a JSON result of boolean data type. If it’s true then it indicate that data deleted from database successfully.

Second, we need to add following code in AngularJSApp–> Employee–> Service.js file which call MVC EmployeeController’s Delete method using angular  $http.post method:

//delete record
this.delete = function (UpdateEmpNo) {
    return $http.post('/Employee/Delete/' + UpdateEmpNo);
}

Third, we need to add following code in AngularJSApp–> Employee–> Controller.js file which will call angular employeeService –> delete method. once delete is successful we are reloading employee data to display updated list.

//delete Employee record
$scope.delete = function (UpdateEmpNo) {
    var deleterecord = employeeService.delete($scope.UpdateEmpNo);
    deleterecord.then(function (d) {
        if (d.data.success === true) {
            loadEmployees();
            alert("Employee deleted succussfully");
        }
        else {
            alert("Employee not deleted.");
        }
    });
}

Finally, we need to add following html code in Views–> Home–> Index.cshtml file which will bind $scope variables using angular expression {{variable}}.

@*Delete Employee record*@
<div class="modal" role="dialog" id="deleteDialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
  <button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="text-info">Are you sure you want to delete the record?</h3>
</div>
<div class="modal-body">
<div>
   Employee ID : {{UpdateEmpNo}}
   Empployee Name : {{UpdateEmpName}}</div>
</div>
<div class="modal-footer">
   <button type="button" class="btn btn-danger"
data-dismiss="modal"
ng-click="delete(UpdateEmpNo)">Delete Record</button>
   <button type="button" class="btn btn-default"
data-dismiss="modal">Close</button></div>
</div>
</div>
</div>

Next, let us update and add code to call ng-click events for Delete/Update operation from buttons.

Step-4: Integrate UPDATE and DELETE button for operations

First, we need to update the button html tags for ng-click events in Views–> Home–> Index.cshtml as per below:

<td style="width:200px;">
  <a href="#" class="btn btn-info" data-toggle="modal"
data-target="#Update" ng-click="getForUpdate(emp)">Update</a>
  <a href="#" class="btn btn-danger" id="btnDelete" data-toggle="modal"
data-target="#deleteDialog" ng-click="getForDelete(emp)">Delete</a></td>

Then add following angular events (getForUpdate & getForDelete) for Update/Delete button click events in AngularJSApp–> Employee–> Controller.js file:

//get single record by ID
$scope.getForUpdate = function (Employee) {
    $scope.UpdateEmpNo = Employee.EmpID;
    $scope.UpdateEmpName = Employee.EmpName;
    $scope.UpdateEmail = Employee.Email;
    $scope.UpdateDeptName = Employee.DeptName;
    $scope.UpdateDesignation = Employee.Designation;
}

//get data for delete confirmation
$scope.getForDelete = function (Employee) {
    $scope.UpdateEmpNo = Employee.EmpID;
    $scope.UpdateEmpName = Employee.EmpName;
}

Above $scope variables are used during data-binding of employee properties when model dialog open for Update/Delete operation.

That’s all. we are all set to run the application now.

Step-5: Run the web application – F5

step-f5-run

Press Add Employee button, it will open model dialog.

step-16-Add-model

Add the details for employee and press save button. currently we are not using any data validation during insert/update operation but in next article we will see how to validation form data before saving it. Once data is saved, it will show alert of operation.

step-17-add-success

Currently we are using simple JavaScript alert to display notification messages for each operations. but in up coming article we will add toaster notification for sexy and beautiful alerts.

Next, let us update any employee data, press Update button for employee you want to update.

step-18-update-model

Update the field values and press Update button to save the data. It will display alert for successful update operation.

step-19-update-success

Now, let us delete employee, it will ask for confirmation before deleting the record

step-20-delete-model

once you confirm, it will delete the record by showing alert.

step-21-delete-success

After deletion, employee list will look like

step-22-after-delete-grid

That’s all for this article. In next article we will add some data validation for insert/update operation using AngularJS. Till than stay tuned 🙂

Please feel free to provide your feedback and comments.

Code for this article is available on GitHub:

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

ASP.NET 5 and AngularJS

Stephen Walther has written multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, he shown how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. Go ahead and read these interesting and informative articles which will add to your learning of ASP.NET 5 with AngularJS.

Following are the topic and link of each blog posts:  

You can download the code discussed in this blog post from GitHub:

https://github.com/StephenWalther/MovieAngularJSApp

Hope this will help !!!