AngularJS MVC Repository

Demo Link: http://technical.cosmicverse.info/employee.

It is a simplest tutorial on AngularJS and Repository Pattern for developing professional MVC Applications. It includes a source code about practical permission management project.

AngularJS MVC Repository Dispose

Introduction

The aim of this article is to clear AngularJS technology and Repository which is one of the useful design pattern in order to developing web applications easy and more professional. There are some fundamental difficulties with the Jquery such as sticking among unstructured code or tangling in deadlocks but AngularJS is able to solve some barriers in Jquery. AngularJS is enough power, specially for CRUD (Create, Read, Update and Delete) web applications, it follows MVC pattern, so our code is neat and clear. Besides it enables us to write less code and testing code has better condition in AngularJS. Albeit these factors do not diminish JQuery power for writing rest of other types of application such as Game or etc.

The other major in this article is to explain repository pattern which encapsulates data access layer and draw a separate line between actual database and other parts of data access layer. It has some advantages for developers for examples; it makes changing and updating data context more convenient and testing frameworks do not run for physical data access code, so this isolation makes it more flexible.

Last but not least is how to debug scripts in web browser for beginners.

I will describe more about each of sections widely, I will open these technologies and pattern within real project in order to having a clear concept from them.

Background

What is Repository

Repository is one of the useful design pattern which hides physical data from the rest of the other sections of data access layers. professionally speaking Repository give us an instruction to how encapsulates our data context from other database queries and data access logic. It is such as a line which isolates actual database from other parts, eventually it makes our web application more convenient to test it layer by layer. Moreover it supplies an in memory like collection List vs IEnumerable vs IQueryable vs ICollection vs IDictionary for accessing domain objects which ignore persistence and enhance performance. So we prefer to use repository in MVC application to have test ability and speed with the flexibility to future changing.

Repository

We have two choices for repository structure. One is building one Repository class and IRepository interface for each entity and another way is creating one GenericRepository class for all of entities and defining basic CRUD (Create, Read, Update, Delete) operations and one UnitOfWork class so that all of repository for each entity should be built on UnitOfWork class. Definitely second way is approved when having too much entities.

As we make for each entity one controller in MVC as a “XController”. We create a folder and name it GenericRepository and make one class “GenericRepository.cs”. Class “GenericRepository.cs” has CRUD functions deal with data context and then create a folder and name it "UnitOfWork" and make one class “UnitOfWork.cs”. you should write inside "UnitOfWork.cs" list of repositories for each entities and moreover "Save()" and "Dispose()" methods. Controllers just have access to UnitOfWork. Therefore you separated your business layer from data layer and whenever you want to change your policy and prefer to use another ORM such as NHibernate you will not have any trouble with high layer such as business layer.

Why Repository with Entity Framework:

It is good question that if we use Entity Framework so why we need to establish another repository above Data Context. Because Data Context is repository itself. Image one day you want to use in Data Access Layer another approaches such as NHibernate, ADO.NET or even XML files or suppose you have to change database from sql to oracle, so your trouble is very small and you have to change just a bit in your code instead of changing almost the whole of your structure and write it again. Therefore Repository Pattern enables us to decouple layers properly and comes in handy when we will change our section specially data layer in future. On the other hand testing will be easily.

Repository with Entity Framework

What is AngularJS

AngularJS is a JavaScript framework for organizing HTML code in a more structural, clear and succinct mode. This client-side technology provides easy and light code in order to make developing and even designing as a simple task. AngularJS eliminates most of redundant code specially in CRUD web application. It is a MV(Whatever you like) pattern and not just a MVC.

There are two kinds of accessories which help us to make a bridge between user interface and the core of business and data layer.

  • Library: These types are set of functions such as JQuery and whenever you use some of them ($.ajax) it will call related function to handle functions.

  • Frameworks: These types are specific structure for implementation application and developer have to follow these structure. Such as durandal and ember.

AngularJS has different approach to work out our needs, angular embeds new properties inside HTML tags such as “ng-model”, “ng-repeat” which are known as Directives in order to fade our barriers to match and transform data.
On the other hand AngularJS has mingled Ajax and HTML DOM in a good structure which I will describe it more as follow:

Angular Advantages:

  1. It is very good for CRUD web application.

  2. It makes testing easy in CRUD web application.

  3. You need to write less code.

  4. You can run your code more quickly.

  5. One of the most popular and famous features in the AngularJS is two way and simple binding.
    1. <input type="text" ng-model="simpleBinding" /><span>{{simpleBinding}}</span>  
  6. You do not need to modify HTML DOM.

  7. By the aid of directives your tasks are more easy and time saving.

  8. By its architecture in MVC or in the better word MVW, decoupling is real and excellent.

Angular Advantages

Design Guidance

As you see in the above picture, you should download angular files and put jquery and angular js files inside script folder. Inside Module.js write name for angular app such as "MyApp" this name relates your angular file to each other and you should use it inside html tag for your view, in this scenario I have used "_Layout.cshtml" as my master view (according to MVC Pattern), in this html tag you should write a directive angular ng-app='MyApp' which hold angular files.

Then you have to introduce these file into your view by <script src=?>.

Index.cshtml inherits from _Layout.cshtml, now by adding another directive as ng-controller='angularCtrl' inside a div, you make a relation between your view and controller.js because angularCtrl is name of Controller.js.

You just need to use simple html tag such as <input type='text'> and add ng-model='empid' directive to this input tag and whenever you want to refer to this input (set or get data) from Controller.js, call it by $Scope.empid.

This same story repeat for <input type='button'> and add ng-click='add()' directive to this input tag and whenever you want to refer to this input (set or get data) from Controller.js call it by $Scope.add().

For representing data inside table in angular you can use simple table tag by the aid of ng-repeat="employee in employees" now whenever you want to (set or get data) from Controller.js you just need to use: $Scope.employees and use expressions such as {{employee.ID}} or {{employee.FirstName}} or other fields.

  1. <table>  
  2.    <tr ng-repeat="employee in employees">  
  3.       <td>  
  4.          {{employee.ID}}  
  5.       </td>  
  6.    </tr>  
  7. </table>  
If you want to write function inside controller.js you should call ServiceName.FunctionName such as angularservice.getEmp(), "angularservice" is the name of Service.js. Now in the "Service.js" you can continue function { "getEmp()" } with $http.get("/ControllerName/ActionName"), or for adding function which you use pass data from view to controller use:

Inside Controller.js to pass data to service.
  1. var Employee = {  
  2.    FirstName: $scope.FirstName ,  
  3.    LastName: $scope.LastName ,  
  4.    UserName: $scope.UserName  
  5. };  
  6.   
  7. angularService.Add(Employee)   
Inside Service.js to pass data to EmployeeController.cs.
  1. this.Add = function (employee) {  
  2.    var response = $http({  
  3.       method: "post",  
  4.       url: "/Employee/Add",  
  5.       data: JSON.stringify(employee),  
  6.       dataType: "json"  
  7.   
  8.    });  
  9.    return response;  
  10. }  
Angularjs vs Jquery

Barriers in the Jquery and Solution in AngularJS:

 

  1. Jquery Problem: If you want to use multiple entities you are not allowed to use multiple model in one view, therefore you have to write viewmodel to support it.

  2. AngularJS Solution: You can handle it by using $Scope object. This tiny and awesome object can supply data and do changes.

  3. Jquery Problem: You have problem to use foreach loop if you are going to use viewmodel, of that you have to use for loop.

  4. AngularJS Solution: You can solve it by using ng-repeat directive inside table {tr tag}.

  5. Jquery Problem: You should manipulate on HTM DOM and customized your requirement according to your model architecture and writing something like that: Html.EditorFor(model => model.ArticleTitle).

  6. AngularJS Solution: But by the aid of AngularJS you can use <input> and just by adding specific directives, you will reach your goal.

How to arrange AngularJS Files:

arrange AngularJS Files
Dispose Pattern

In order to know Dispose pattern, it is necessary to know Garbage Collection.

Garbage Collection

When you create object from data type Common Language Runtime (CRL) assigns specific space inside memory for your new object, in this process Managed Heap helps to CLR to allocate object to memory. Memory space is finite and it is not possible that many objects as consumers use resources. Indeed we need a tool to release memory from objects which do not use memory for long time and they were not called by applications for a while. Garbage Collector is proper tool to manage memory and release space from old and useless objects.

IDisposable is an interface to release resources for particular reclaiming resources whose their life time is well known for programmer. Its advantages are high speed allocation service without long term fragmentation problems.

In the below picture you see three stages, first one objects with these names "A", "B", "C" has taken resources as it is obvious "A" and "B" are dead whereas "C" is live, on the other hand our new objects "D", "E" and "F" are in the queue to use resources. Suppose if there is no tools to stop and release memory or resources so we other objects must wait long in the queue and the performance comes down. Garbage Collection comes here to help us and gather "A" and "B" and takes them from resource due to they are old and no application uses them in long term. So in second stage we have more free space and "D", "E" and "F" will come in third stage. Dispose method or in a better word "Dispose Pattern" helps us to have more performance. Especially when we know life time of the resource (context).

Garbage Collection

  1. class X : IDisposable  
  2.     {  
  3.   
  4.         //Define Flag: Show us if dispose has been called or not   
  5.         bool disposed = false;  
  6.   
  7.         // Public implementation of Dispose pattern callable by consumers.  
  8.         public void Dispose()  
  9.         {  
  10.             Dispose(true);  
  11.             //Using SuppressFinalize helps us to do not finalize object later  
  12.             GC.SuppressFinalize(this);  
  13.         }  
  14.   
  15.   
  16.         // Protected implementation of Dispose pattern and allow to override it later   
  17.         protected virtual void Dispose(bool disposing)  
  18.         {  
  19.             if (disposed)  
  20.                 return;  
  21.   
  22.             if (disposing)  
  23.             {  
  24.                 //Free any other managed objects here.   
  25.                 context.Dispose();  
  26.             }  
  27.   
  28.             // Free any unmanaged objects here.   
  29.             disposed = true;  
  30.         }  
  31.   
  32.   
  33.         ~X()  
  34.         {  
  35.             // release resources  
  36.             Dispose(false);  
  37.   
  38.         }  
  39.     };  
  40.   
  41.   
  42.     //Calling dispose inside Controller:  
  43.     protected override void Dispose(bool disposing)  
  44.     {  
  45.         X.Dispose();  
  46.         base.Dispose(disposing);  
  47.     }  
How to install AngularJS

 

  • Go to -> Tools Menu -> Library Package Manager -> Package Manager Console.

  • Write in commanc line: Install-Package angularjs -Version 1.3.8.

  • Be careful about varient angular version due to it might need a bit different code style.

Package Manager Console

Using the code

Scenario:

I want to follow permission management scenario to explain better these concepts (AngularJS and Repository in MVC). It includes two pages, first on just do CRUD functions, creating employees, reading or selecting employees, updating and deleting their information, besides them it mentions to other facilities in Angular such as routing, filtering. Second page assigns permission for each of employees, here you need to have combo box to keep employees name and permission roles. Therefore it covers fundamental requirements in dealing with have a robust MVC web application.

1. Employee CRUD (Create Read Update Delete): This page shows data and user can edit and delete or add new employee to it.

add new employee

2. AngularJS is able to filter data:

filter data

3. When user clicks on "Edit" button -> "Update Employee" section appears.

Update Employee

4. When user clicks on "Add" button -> "Add Employee" section appears. Finally by clicking on "Permission" link, angular leads you to permission page by routing facility.

Permission

5. User can assign permission to specific employee by selecting his or her name from combobox.

combobox

6. Loading Data inside combobox.

Loading Data inside

Step By Step Using Repository and AngularJS in your MVC Project (Instruction as Cookbook):

  1. Create Database and name it "MVCAdvanced".

  2. Create two Tables: "Employee" and "EmpRole".

    EmpRole

  3. Create New MVC Project for have more information see here.

  4. Create New Data Model for have more information see here.

  5. Create New Folder in Solution and name it "GenericRepository".

  6. Create "GenericRepository.cs" Class.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Data;  
    4. using System.Data.Entity;  
    5. using System.Linq;  
    6. using System.Linq.Expressions;   
    7.   
    8. namespace MvcAdvanced.GenericRepository  
    9. {  
    10.     public class GenericRepository<TEntity> where TEntity : class  
    11.     {  
    12.         internal MvcAdvancedEntities context;  
    13.         internal DbSet<TEntity> dbSet;  
    14.   
    15.         public GenericRepository(MvcAdvancedEntities context)  
    16.         {  
    17.             this.context = context;  
    18.             this.dbSet = context.Set<TEntity>();  
    19.         }  
    20.                         
    21.         public virtual IEnumerable<TEntity> Get()  
    22.         {  
    23.             IQueryable<TEntity> query = dbSet;  
    24.             return query.ToList();  
    25.         }  
    26.   
    27.         public virtual TEntity GetByID(object id)  
    28.         {  
    29.             return dbSet.Find(id);  
    30.         }  
    31.   
    32.         public virtual void Insert(TEntity entity)  
    33.         {  
    34.             dbSet.Add(entity);  
    35.         }  
    36.   
    37.         public virtual void Delete(object id)  
    38.         {  
    39.             TEntity entityToDelete = dbSet.Find(id);  
    40.             Delete(entityToDelete);  
    41.         }  
    42.   
    43.         public virtual void Delete(TEntity entityToDelete)  
    44.         {  
    45.             if (context.Entry(entityToDelete).State == EntityState.Detached)  
    46.             {  
    47.                 dbSet.Attach(entityToDelete);  
    48.             }  
    49.             dbSet.Remove(entityToDelete);  
    50.         }  
    51.   
    52.         public virtual void Update(TEntity entityToUpdate)  
    53.         {  
    54.             dbSet.Attach(entityToUpdate);  
    55.             context.Entry(entityToUpdate).State = EntityState.Modified;  
    56.         }  
    57.   
    58.     }  
    59.   
    60. }  
  7. Create "UnitOfWork" Folder and Create a class "UnitOfWork.cs".
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using MvcAdvanced.GenericRepository;  
    6.   
    7. namespace MvcAdvanced.UnitOfWork  
    8. {  
    9.     public class UnitOfWork : IDisposable  
    10.     {  
    11.         private MvcAdvancedEntities context = new MvcAdvancedEntities();  
    12.          
    13.         private GenericRepository<Employee> employeeRepository;  
    14.         private GenericRepository<EmpRole> empRoleRepository;  
    15.   
    16.         public GenericRepository<Employee> EmployeeRepository  
    17.         {  
    18.             get  
    19.             {  
    20.                 if (this.employeeRepository == null)  
    21.                     this.employeeRepository = new GenericRepository<Employee>(context);  
    22.                 return employeeRepository;  
    23.             }  
    24.         }  
    25.   
    26.         public GenericRepository<EmpRole> EmpRoleRepository  
    27.         {  
    28.             get  
    29.             {  
    30.                 if (this.empRoleRepository == null)  
    31.                     this.empRoleRepository = new GenericRepository<EmpRole>(context);  
    32.                 return empRoleRepository;  
    33.             }  
    34.         }     
    35.   
    36.         public void Save()  
    37.         {  
    38.             context.SaveChanges();  
    39.         }  
    40.   
    41.         private bool disposed = false;  
    42.         protected virtual void Dispose(bool disposing)  
    43.         {  
    44.             if (disposed)  
    45.             return;  
    46.   
    47.             if (disposing)  
    48.             {  
    49.                 //Free any other managed objects here.   
    50.                 context.Dispose();  
    51.             }  
    52.   
    53.             // Free any unmanaged objects here.   
    54.             disposed = true;  
    55.         }  
    56.         public void Dispose()  
    57.         {  
    58.             Dispose(true);  
    59.             GC.SuppressFinalize(this);  
    60.         }  
    61.   
    62.     }  
    63. }  
  8. Create "EmployeeController" inside "Controller" Folder.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6. using MvcAdvanced.GenericRepository;  
    7. using AutoMapper;  
    8.   
    9. namespace MvcAdvanced.Controllers  
    10. {  
    11.     public class EmployeeController : Controller  
    12.     {  
    13.         private UnitOfWork.UnitOfWork unitOfWork = new UnitOfWork.UnitOfWork();  
    14.              
    15.         public ActionResult Index()  
    16.         {  
    17.             return View();  
    18.         }  
    19.   
    20.         public JsonResult GetAllEmployees()  
    21.         {  
    22.             var employeeList = (List<Employee>)unitOfWork.EmployeeRepository.Get();  
    23.             return Json(employeeList, JsonRequestBehavior.AllowGet);  
    24.         }  
    25.   
    26.         public string Update(Employee employee)  
    27.         {   
    28.             if (employee != null)  
    29.             {  
    30.                 var emp = unitOfWork.EmployeeRepository.GetByID(employee.ID);  
    31.                 emp.FirstName = employee.FirstName;  
    32.                 emp.LastName = employee.LastName;  
    33.                 emp.UserName = employee.UserName;  
    34.                  
    35.                 unitOfWork.EmployeeRepository.Update(emp);  
    36.                 unitOfWork.Save();                      
    37.                  
    38.                return "Record has been Updated";  
    39.                  
    40.             }  
    41.             else  
    42.             {  
    43.                 return "Record has Not been Updated";  
    44.             }  
    45.         }  
    46.   
    47.         public string Delete(int id)  
    48.         {  
    49.             try  
    50.             {  
    51.                 if (id != null)  
    52.                 {  
    53.                     unitOfWork.EmployeeRepository.Delete(id);  
    54.                     unitOfWork.Save();  
    55.   
    56.                     return "Employee Has Been Deleted";  
    57.                 }  
    58.                 else  
    59.                 {  
    60.                     return "Employee Hasnot Been Deleted";  
    61.                 }  
    62.             }  
    63.             catch  
    64.             {  
    65.                 return "Employee Hasnot Been Deleted";  
    66.             }  
    67.         }  
    68.   
    69.         public string Add(Employee employee)  
    70.         {  
    71.             try  
    72.             {  
    73.                 if (employee != null)  
    74.                 {  
    75.                     unitOfWork.EmployeeRepository.Insert(employee);  
    76.                     unitOfWork.Save();  
    77.                     return "Record has been Added";  
    78.                 }  
    79.                 else  
    80.                 {  
    81.                     return "Record has Not been Verified";  
    82.                 }  
    83.             }  
    84.   
    85.             catch  
    86.             {  
    87.                 return "Record has Not been Added";  
    88.             }  
    89.         }  
    90.   
    91.         protected override void Dispose(bool disposing)  
    92.         {  
    93.             unitOfWork.Dispose();  
    94.             base.Dispose(disposing);  
    95.         }  
    96.                  
    97.     }  
    98. }  
  9. Create "PermissionController" inside "Controller" Class.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6. using MvcAdvanced.GenericRepository;  
    7.   
    8. namespace MvcAdvanced.Controllers  
    9. {  
    10.     public class PermissionController : Controller  
    11.     {  
    12.         private UnitOfWork.UnitOfWork unitOfWork = new UnitOfWork.UnitOfWork();  
    13.          
    14.         public ActionResult Index()  
    15.         {  
    16.             return View();  
    17.         }  
    18.   
    19.         public JsonResult GetAllEmpRole()  
    20.         {  
    21.             var employeeList = unitOfWork.EmpRoleRepository.Get();  
    22.             return Json(employeeList, JsonRequestBehavior.AllowGet);  
    23.         }  
    24.           
    25.         public JsonResult GetAllEmpNames()  
    26.         {  
    27.             var employeeList = unitOfWork.EmployeeRepository.Get();  
    28.             return Json(employeeList, JsonRequestBehavior.AllowGet);  
    29.         }  
    30.   
    31.         public JsonResult GetAllRoles()  
    32.         {  
    33.             var roleList = (from emp in unitOfWork.EmployeeRepository.Get() join role in unitOfWork.EmpRoleRepository.Get() on emp.RoleID equals role.ID select new { emp.ID, emp.FirstName, emp.LastName, emp.UserName, role.Role }).ToList();  
    34.             return Json(roleList, JsonRequestBehavior.AllowGet);  
    35.         }  
    36.   
    37.         public string UpdateRole(Employee permission)  
    38.         {  
    39.   
    40.             if (permission != null)  
    41.             {  
    42.                 var emp = unitOfWork.EmployeeRepository.GetByID(permission.ID);  
    43.                 emp.RoleID = permission.RoleID;  
    44.                  
    45.                 unitOfWork.EmployeeRepository.Update(emp);  
    46.                 unitOfWork.Save();  
    47.   
    48.                 return "Record has been Updated";  
    49.             }  
    50.             else  
    51.             {  
    52.                 return "Record has Not been Updated";  
    53.             }  
    54.         }  
    55.   
    56.         protected override void Dispose(bool disposing)  
    57.         {  
    58.             unitOfWork.Dispose();  
    59.             base.Dispose(disposing);  
    60.         }  
    61.   
    62.     }  
    63. }  
  10. Downloading angularjs from.

    I have used angularjs version 1.3.8. Something (code style) might be changed version by version. Put angular.js and angular-route.js inside "Scripts" folder.

  11. Create Angular Files:.

    In the "Content" folder make new folder and name it "Angular", then create three javascript files inside it and name them: { Module.js, Controller.js, Service.js }.

  12. Inside Module.js write:
    1. var app = angular.module('MyApp', ['ngRoute']);  
    2.   
    3. app.config(['$routeProvider',function ($routeprovider) {  
    4.       $routeprovider.  
    5.         when('/employee', {  
    6.             templateurl: '/Views/Employee/index.cshtml',  
    7.             controller: 'AngularCtrl'  
    8.         }).  
    9.         when('/permission', {  
    10.             templateurl: '/Views/Permission/index.cshtml',  
    11.             controller: 'AngularCtrlRole'  
    12.         }).  
    13.         otherwise({  
    14.             redirectto: '/employee'  
    15.         });  
    16.   }]);  
  13. Inside Views -> Shared -> _Layout.cshtml write: (you are introducing your application name "MyApp" to your view by adding ng-app).
    1. <!DOCTYPE html>  
    2. <html ng-app='MyApp'>  
    3. <head>  
    4.     <meta charset="utf-8" />  
    5.     <meta name="viewport" content="width=device-width" />  
    6.     <title>@ViewBag.Title</title>  
    7.    <script src="~/Scripts/angular.js"></script>  
    8.      <script src="~/Scripts/angular.min.js"></script>  
    9.     <script src="~/Scripts/angular-route.js"></script>  
    10.   <script src="~/Content/Angular/Module.js"></script>  
    11.     <script src="~/Content/Angular/Service.js"></script>  
    12.     <script src="~/Content/Angular/Controller.js"></script>  
    13.   
    14.     @Styles.Render("~/Content/css")  
    15.      
    16. </head>  
    17. <body>  
    18.     @RenderBody()  
    19.   
    20.     @Scripts.Render("~/bundles/jquery")  
    21.     @RenderSection("scripts", required: false)  
    22. </body>  
    23. </html>  
  14. Inside Views -> Employee -> Index.cshtml write:
    1. @{  
    2.     ViewBag.Title = "Index";  
    3. }  
    4.    
    5. <h2>Index</h2>  
    6. <div ng-controller="AngularCtrl">  
    7.     <a href="/permission">Permission</a><br />  
    8.       
    9.   Filter: <input type="text" value="Name" ng-model="FilterByFirstName" />  
    10.   <br />  
    11.        
    12.     
    13.     <br />  
    14.      <input type="button" value="Add" ng-click="add()" />  
    15.         <table cellpadding="12">  
    16.             <tr>  
    17.                 <td><b>ID</b></td>  
    18.                 <td><b>FirstName</b></td>  
    19.                 <td><b>LastName</b></td>  
    20.                 <td><b>UserName</b></td>  
    21.                 <td><b>Operation</b></td>  
    22.             </tr>  
    23.             <tr ng-repeat="employee in employees | filter:FilterByFirstName ">  
    24.                  
    25.                 <td>  
    26.                     {{employee.ID}}  
    27.                 </td>  
    28.                 <td>  
    29.                     {{employee.FirstName}}  
    30.                 </td>  
    31.                 <td>  
    32.                     {{employee.LastName}}  
    33.                 </td>  
    34.                 <td>  
    35.                     {{employee.UserName}}  
    36.                 </td>  
    37.                <td>  
    38.                      <input type="button" value="Edit" ng-click="edit(employee)" />  
    39.                      <input type="button" value="Delete" ng-click="delete(employee)" />  
    40.                       
    41.                 </td>  
    42.                 
    43.             </tr>  
    44.              
    45.         </table>  
    46.      <div ng-show="divEmpModification">  
    47.         <p>{{Operation}} Employee</p>  
    48.         <table>  
    49.             <tr>  
    50.                  
    51.                 <td>  
    52.                     <input type="text" style="width:20px;"  disabled="disabled" ng-model="ID" />  
    53.                 </td>  
    54.               
    55.                  
    56.                 <td>  
    57.                     <input type="text" style="width:94px;" ng-model="FirstName" />  
    58.                 </td>  
    59.               
    60.                 
    61.                 <td>  
    62.                     <input type="text" style="width:94px;" ng-model="LastName" />  
    63.                 </td>  
    64.              
    65.                  
    66.                 <td>  
    67.                     <input type="text" style="width:94px;" ng-model="UserName" />  
    68.                 </td>  
    69.                  
    70.                 <td colspan="2">  
    71.                     <input type="button"  value="Save" ng-click="Save()" />  
    72.                 </td>  
    73.             </tr>  
    74.         </table>  
    75.     </div>  
    76.   
    77.     </div>  
  15. Inside Views -> Permission -> Index.cshtml write:
    1. <h2>Index</h2>  
    2. <div ng-controller="AngularCtrlRole">  
    3.      <a href="/employee">Employee</a>  
    4.     <p ng-model="mahsa"> ID of selected LastName is : {{selectedItem.ID}} </p>  
    5.      
    6.         <select data-ng-Model="selectedItem" ng-options="item.LastName for item in items">  
    7.       </select>  
    8.   
    9.     <p> ID of selected Role is : {{selectedItemRole.ID}} </p>  
    10.      
    11.      <select ng-model="selectedItemRole" ng-options="roleitem.Role for roleitem in roleitems">  
    12.       </select>  
    13.   
    14.      <input type="button" value="Save Permission" ng-click="SavePermission()" />  
    15.   
    16.       
    17.         <table cellpadding="12">  
    18.             <tr>  
    19.                 <td><b>ID</b></td>  
    20.                 <td><b>First Name</b></td>  
    21.                 <td><b>Last Name</b></td>  
    22.                 <td><b>User Name</b></td>  
    23.                 <td><b>Role Name</b></td>  
    24.             </tr>  
    25.             <tr ng-repeat="view in views ">  
    26.                  
    27.                 <td>  
    28.                     {{view.ID}}  
    29.                 </td>  
    30.                 <td>  
    31.                     {{view.FirstName}}  
    32.                 </td>  
    33.                 <td>  
    34.                     {{view.LastName}}  
    35.                 </td>  
    36.                 <td>  
    37.                     {{view.UserName}}  
    38.                 </td>  
    39.                 <td>  
    40.                     {{view.Role}}  
    41.                 </td>  
    42.              
    43.                 
    44.             </tr>  
    45.              
    46.       </table>  
    47.   
    48.        
    49.  </div>  
  16. Inside Content -> Angular -> Controller.js write:
    1. app.controller("AngularCtrl", function ($scope, angularService) {  
    2.     $scope.divEmpModification = false;  
    3.     GetAll();  
    4.     //To Get All Records    
    5.     function GetAll() {  
    6.         var Data = angularService.getEmp();  
    7.             Data.then(function (emp) {  
    8.             $scope.employees = emp.data;  
    9.         }, function () {  
    10.             alert('Error');  
    11.         });  
    12.     }  
    13.   
    14.     $scope.edit = function (employee) {  
    15.              
    16.             $scope.ID = employee.ID;  
    17.             $scope.FirstName = employee.FirstName;  
    18.             $scope.LastName = employee.LastName;  
    19.             $scope.UserName = employee.UserName;  
    20.             $scope.Password = employee.Password;  
    21.             $scope.Operation = "Update";  
    22.             $scope.divEmpModification = true;       
    23.     }  
    24.   
    25.     $scope.add = function () {  
    26.   
    27.         $scope.ID ="";  
    28.         $scope.FirstName = "";  
    29.         $scope.LastName = "";  
    30.         $scope.UserName = "";  
    31.         $scope.Password = "";  
    32.         $scope.Operation = "Add";  
    33.         $scope.divEmpModification = true;  
    34.     }  
    35.   
    36.     $scope.Save = function () {  
    37.         var Employee = {  
    38.             FirstName: $scope.FirstName ,  
    39.             LastName: $scope.LastName ,  
    40.             UserName: $scope.UserName,  
    41.             Password: $scope.Password   
    42.         };  
    43.         var Operation = $scope.Operation;  
    44.   
    45.         if (Operation == "Update") {  
    46.             Employee.ID = $scope.ID;  
    47.             var getMSG = angularService.update(Employee);  
    48.             getMSG.then(function (messagefromController) {  
    49.                 GetAll();  
    50.                 alert(messagefromController.data);  
    51.                 $scope.divEmpModification = false;  
    52.             }, function () {  
    53.                 alert('Update Error');  
    54.             });  
    55.         }  
    56.         else {  
    57.             var getMSG = angularService.Add(Employee);  
    58.             getMSG.then(function (messagefromController) {  
    59.                 GetAll();  
    60.                 alert(messagefromController.data);  
    61.                 $scope.divEmpModification = false;  
    62.             }, function () {  
    63.                 alert('Insert Error');  
    64.             });  
    65.         }  
    66.     }  
    67.   
    68.     $scope.delete = function (employee) {  
    69.         var getMSG = angularService.Delete(employee.ID);  
    70.         getMSG.then(function (messagefromController) {  
    71.             GetAll();  
    72.             alert(messagefromController.data);  
    73.         }, function () {  
    74.             alert('Delete Error');  
    75.         });  
    76.     }  
    77. });  
    78.   
    79. app.controller("AngularCtrlRole", function ($scope, angularServiceRole) {  
    80.     GetAllNames();  
    81.     GetAllRoles();  
    82.     GetAllEmpRole();  
    83.     //To Get All Records    
    84.     function GetAllEmpRole() {  
    85.         var Data = angularServiceRole.getEmpRole();  
    86.         Data.then(function (emp) {  
    87.             $scope.views = emp.data;  
    88.         }, function () {  
    89.             alert('Error');  
    90.         });  
    91.     }  
    92.   
    93.     //To Get All Records    
    94.     function GetAllNames() {  
    95.         var Data = angularServiceRole.getName();  
    96.         Data.then(function (emp) {  
    97.             $scope.items = emp.data;  
    98.         }, function () {  
    99.             alert('Error');  
    100.         });  
    101.     }  
    102.   
    103.     function GetAllRoles() {  
    104.         var Data = angularServiceRole.getRole();  
    105.         Data.then(function (role) {  
    106.             $scope.roleitems = role.data;  
    107.         }, function () {  
    108.             alert('Error');  
    109.         });  
    110.     }  
    111.   
    112.     $scope.SavePermission = function () {  
    113.         var Permission = {  
    114.             ID: $scope.selectedItem.ID,  
    115.             RoleID: $scope.selectedItemRole.ID  
    116.          };  
    117.              
    118.         var getMSG = angularServiceRole.updateRole(Permission);  
    119.             getMSG.then(function (messagefromController) {  
    120.                 GetAllNames();  
    121.                 GetAllRoles();  
    122.                 GetAllEmpRole();  
    123.                 alert(messagefromController.data);  
    124.               }, function () {  
    125.                 alert('Save Permission Error');  
    126.             });  
    127.          
    128.          
    129.     }  
    130.   
    131. });  
  17. Inside Service.js write:
    1. app.service("angularService", function ($http) {  
    2.   
    3.         this.getEmp = function () {  
    4.             return $http.get("/Employee/GetAllEmployees");  
    5.         };  
    6.   
    7.          
    8.   
    9.     //Save (Update)    
    10.         this.update = function (employee) {  
    11.             var response = $http({  
    12.                 method: "post",  
    13.                 url: "/Employee/Update",  
    14.                 data: JSON.stringify(employee),  
    15.                 dataType: "json"  
    16.             });  
    17.             return response;  
    18.         }  
    19.   
    20.     //Delete   
    21.         this.Delete = function (empID) {  
    22.             var response = $http({  
    23.                 method: "post",  
    24.                 url: "/Employee/Delete",  
    25.                 params: {  
    26.                     id: empID  
    27.                 }  
    28.             });  
    29.             return response;  
    30.         }  
    31.   
    32.     //Add   
    33.         this.Add = function (employee) {  
    34.             var response = $http({  
    35.                 method: "post",  
    36.                 url: "/Employee/Add",  
    37.                 data: JSON.stringify(employee),  
    38.                 dataType: "json"  
    39.                   
    40.             });  
    41.             return response;  
    42.         }  
    43.      
    44. });  
    45.   
    46. app.service("angularServiceRole", function ($http) {  
    47.     this.getEmpRole = function () {  
    48.         return $http.get("/Permission/GetAllEmpRole");  
    49.     };  
    50.   
    51.     this.getName = function () {  
    52.         return $http.get("/Permission/GetAllEmpNames");  
    53.     };  
    54.     this.getRole = function () {  
    55.         return $http.get("/Permission/GetAllRoles");  
    56.     };  
    57.           
    58.     //Save Permission    
    59.     this.updateRole = function (permission) {  
    60.         var response = $http({  
    61.             method: "post",  
    62.             url: "/Permission/UpdateRole",  
    63.             data: JSON.stringify(permission),  
    64.             dataType: "json"  
    65.         });  
    66.         return response;  
    67.     }  
    68. });  

References

History

  • First Version: 1/26/2015
  • Second Version: 1/29/2015 : Making one Repository for entities
  • Third Version: 02/15/2015 : Repository Pattern with GenericRepository and UnitOfWork +Graph Explaination

Feedback

Feel free to leave any feedback on this article; it is a pleasure to see your comments and vote about this code. If you have any questions, please do not hesitate to ask me here.