CRUD, Paging, Sorting, Searching With AngularJS In MVC

Introduction  

  • When selecting the latest technologies, several factors come into play, including how these technologies will be integrated with our project.
  • This article solves the problem for beginners who start working with AngularJS and MVC.
  • Here I have toldyou each and every aspect of the AngularJS to use with what, why, and how.
          
Starting with the database
  • Firstly Create database named TestData.
  • After creating the database create a table with the name EmployeeDesignation, and Department.

          

         
  • Set the Id column as primary key and auto increment id in every table.
  • Database work is done here.
Download the requred js and css files from below given links
Be familiar with the things before proceeding
  • Modules are used to separate the logics for application.
  • var app = angular.module("myApp", ['angularUtils.directives.dirPagination']);
  • Here in the code we declare the application myApp module using angular.module, And in the array we pass the dependent modules, like in this we pass the dependent module for paging.
  • We use the module using ng-app directive in the html page.
  • AngularJS mainly depedent on controllers to control the data and its flow.
  • When the page loads each time the Controller.js file also loads and methods called on load will be executed.
  • The controller contains the objects of javascript containing functions,method and properties.
  • Each controller accepts $scope as a parameter which refers to the application.
  • We use the controller using ng-controller in the html page.
  • Services are the javascript functions that does the certain tasks told by the controller.AngularJs has many inbuilt services like $http,$location,$route,$window.Each service will does specific task.For example : $http is used for ajax call to the server.
  • Service deals with the server code and call the action results specified in the ajax url and response back to the service.
  • The service then returns response to the controller.js and controller.js deals with the views and displays the data on page.
Start with the Code
  • Open the VS2012, Create New ASP.Net MVC4 Web Application, and give the Name BootstrapAngularMvc.
  • Go to Models Folder in the solution explorer of visual studio.
  • Right click the Models folder and find ADD >>> ADO.NET Entity Data Model. Select ADO.NET Entity Data Model.
  • Provide the name DBModel. After that pop up will appear .

           

  • Select generate from database and click next.
               
  • In the below given box type entity name as SahilEntities and After that click New connection.     

           

  • Select Sql server authentication and fill the credentials like server name, user name, password, and then select your database from the database list.

           

  • Check the checkboxes of tables and click on finish.
After that go to the controller folder and Create EmployeeController 
  • In the Controller first replace ActionResult Index with Employee that returns employee view.
  • After that getAll Method called when page is loaded it gets the data from database and returns to service in JSON format.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using BootstrapAngularMvc.Models;  
  7.   
  8. namespace BootstrapAngularMvc.Controllers  
  9. {  
  10. public class EmployeeController : Controller  
  11. {  
  12. public ActionResult Employee()  
  13. {  
  14. return View();  
  15. }  
  16.   
  17. //For getting the all records from database.  
  18. public JsonResult getAll()  
  19. {  
  20. using (SahilEntities dataContext = new SahilEntities())  
  21. {  
  22. var employeeList = (from E in dataContext.Employees  
  23. join dep in dataContext.Departments on E.DepartmentID equals dep.Id  
  24. join dsg in dataContext.Designations on E.DesignationID equals dsg.Id  
  25. orderby E.Id  
  26. select new  
  27. {  
  28. E.Id,  
  29. E.name,  
  30. E.DOB,  
  31. E.Gender,  
  32. E.Email,  
  33. E.Mobile,  
  34. E.Address,  
  35. E.JoiningDate,  
  36. dep.DepartmentName,  
  37. E.DepartmentID,  
  38. dsg.DesignationName,  
  39. E.DesignationID  
  40. }).ToList();  
  41. var JsonResult = Json(employeeList, JsonRequestBehavior.AllowGet);  
  42. JsonResult.MaxJsonLength = int.MaxValue;  
  43. return JsonResult;  
  44. }  
  45. }  
  46. }  
  47. }  
Change application startup controller and action
  • Find RouteConfig.cs in App_Start folder and change the code.
  • In this code we change the action and controller path.
  • Here  those action and controller names are defined which loaded first time when the application was started.
  1.  using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace BootstrapAngularMvc  
  9. {  
  10. public class RouteConfig  
  11. {  
  12. public static void RegisterRoutes(RouteCollection routes)  
  13. {  
  14. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16. routes.MapRoute(  
  17. name: "Default",  
  18. url: "{controller}/{action}/{id}",  
  19. defaults: new { controller = "Employee", action = "Employee", id = UrlParameter.Optional }  
  20. );  
  21. }  
  22. }  
  23. }  
Add Module.js,Controller.js,Service.js in content folder
  • Here we register the module with the application.
  • Here myApp is the module name that we used with ng-app directive in HTML view.
  • In Module.js write the given code.
  1. var app = angular.module("myApp", []);  
  • In Controller.js write the given code.
  • myCntrl is the controller name that is registered with the myApp module and used in HTML view with ng-controller directive.
  • $scope is used to refers to the application.Data passed to $scope in controller is accessible in  view.
  • myService is the name of service that is used with controller to call the functions from server.
  • Here sort function serves the purpose of sorting according to the columns like sort by name,id,address etc.
  • keyName is passed to the sort function from grid placed in view by clicking on the header of grid.
  • GetAllEmployees function calls the getEmployees function from service.Service returns the response to controller.
  • Data returned from service is in json format and that data is stored in $scope and $scope is accessed in view.
  1.  app.controller("myCntrl"function ($scope, myService) {  
  2. GetAllEmployees();  
  3.   
  4. //For sorting according to columns  
  5. $scope.sort = function (keyname) {  
  6. $scope.sortKey = keyname;  
  7. $scope.reverse = !$scope.reverse;  
  8. }  
  9.   
  10. //To Get All Records  
  11. function GetAllEmployees() {  
  12. var getData = myService.getEmployees();  
  13.   
  14. getData.then(function (emp) {  
  15. $scope.employees = emp.data;  
  16. }, function (emp) {  
  17. alert("Records gathering failed!");  
  18. });  
  19. }  
  20. });  
  • In Service.js write the given code.
  • myService is the name of the service registers with the myApp module.
  • $http is passed as parameter. $http serves the purpose for ajax call to the server.
  • In this service  getEmployees function is used to call the getAll server method by providing url.
  • This method returns the response to the controller.     
  1. app.service("myService"function ($http) {  
  2.   
  3. //get All Employee  
  4. this.getEmployees = function () {  
  5. return $http.get("/Employee/getAll");  
  6. };  
  7. });  
Add view from the controller
  • Right click the Employee action of the EmployeeController and select add view option.
  • Write the code in Employee.cshtml.
  • In View HTML tag is used with the directive ng-app. ng-app calls the myApp module to initialize with this view.
  • After that all the css and script files are dropped in head tag.
  • ng-controller directive is used with the div tag to initialize with the controller we created.
  • <div class="container" ng-controller="myCntrl"> . Here ng-controller is a directive and myCntrl is the name of controller we specify in the controller.js file.
  • ng-click directive is used with the input button to call the method from controller. ng-click="AddEmployeeDiv();". Here ng-click is directive and AddEmployeeDiv() is a function.
  • ng-model directive binds an form control to the property on $scope using ng-model controller.
  • In ng-model we pass search that performs search operation automatically.
  • After that on table th click we pass the sort funtion with the column name as key to sort with.
  • Span class is used here for showing glyphicons based on increasing and decreasing orders. ng-show is used with the sort key.
  • ng-show is used to hide or show the html element based on given expression.
  • <tr dir-paginate="employee in employees|orderBy:sortKey:reverse|filter:search|itemsPerPage:10" ng-model="search">.
  • Here is the line of code that is responsible for data binding,sorting,searching,paging.
  • dir-paginate is used to get the data from the $scope.In the $scope employess the data is passed and that data is accessed here with the employee instance name.
  • orderBy is used with the $scope sortKey and sort the records accordingly.
  • filter is used to provide the search keyword that is define in the input tag written above.
  • itemsPerPage solves the problem of displaying item on a page.
  • ng-model search is used to show pages according to search.
  • Data Binding is resolved with this {{employee.Id}}. This binds the Id column.Column name should be same as in the database.
  • ng-click is used with the button to call the editEmployee function in the controller.Instance employee is passed in the editEmployee function.
  1. <dir-pagination-controls    
  2. max-size="10"    
  3. direction-links="true"    
  4. boundary-links="true">    
  5. </dir-pagination-controls>         
  • This tag serves the purpose of paging, use of this tag is mandatory.
  • max-size is used to specify the no of records on a page.
  • directionlinks are used to give the next and previous buttons.
  • boundaryLinks are used to give the first and last button.
  • After that bootstrap modal is created for showing up fields that is used for inserting and updating the employee data.
  • In the footer of modal AddUpdateEmployee() function is called to save or update the data on click of Save.
  • And the last is alert modal for displaying any alert messages on save or update.
  1.  @{  
  2. ViewBag.Title = "Employee";  
  3. }  
  4.   
  5. <html ng-app="myApp">  
  6. <head>  
  7. <title></title>  
  8. <script src="~/Content/angular1.2.18.min.js"></script>  
  9. <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  10. <script src="~/Content/bootstrap.min.js"></script>  
  11. <script src="~/Content/Module.js"></script>  
  12. <script src="~/Content/Controller.js"></script>  
  13. <script src="~/Content/Service.js"></script>  
  14. <script src="~/Content/dirPagination.js"></script>  
  15.   
  16. <style>  
  17. table {  
  18. border-collapse: collapse;  
  19. border-spacing: 0;  
  20. width: 100%;  
  21. border: 1px solid #ddd;  
  22. }  
  23.   
  24. th, td {  
  25. border: none;  
  26. text-align: left;  
  27. padding: 8px;  
  28. }  
  29. </style>  
  30. </head>  
  31. <body>  
  32. <div class="container" ng-controller="myCntrl">  
  33.   
  34. <input type="button" class="btn btn-success btn-lg" ng-click="AddEmployeeDiv();" value=" Add Employee" style="margin-left: 15px;" data-toggle="modal" data-target="#myModal" />  
  35. <hr style="width: 550px;" />  
  36.   
  37. <form class="form-inline">  
  38. <div class="form-group">  
  39. <b>Search : </b>  
  40. <input type="text" placeholder="Search" class="form-control" ng-model="search" />  
  41. </div>  
  42. </form>  
  43. <br />  
  44. <table cellpadding="12" class="table table-bordered table-hover table-striped">  
  45. <tr class="success">  
  46. <th style="cursor: pointer;" ng-click="sort('id')"><b>Employee ID</b> <span class="glyphicon sort-icon" ng-show="sortKey=='id'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span></th>  
  47. <th style="cursor: pointer;" ng-click="sort('Name')"><b>Name</b> <span class="glyphicon sort-icon" ng-show="sortKey=='Name'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span></th>  
  48. <th style="cursor: pointer; width: 100px;" ng-click="sort('DOB')"><b>DOB</b> <span class="glyphicon sort-icon" ng-show="sortKey=='DOB'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span></th>  
  49. <th style="cursor: pointer;" ng-click="sort('Gender')"><b>Gender</b> <span class="glyphicon sort-icon" ng-show="sortKey=='Gender'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span></th>  
  50. <th style="cursor: pointer;" ng-click="sort('Email')"><b>Email</b> <span class="glyphicon sort-icon" ng-show="sortKey=='Email'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span></th>  
  51. <th style="cursor: pointer;" ng-click="sort('Mobile')"><b>Mobile</b> <span class="glyphicon sort-icon" ng-show="sortKey=='Mobile'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span></th>  
  52. <th style="cursor: pointer;" ng-click="sort('Address')"><b>Address</b> <span class="glyphicon sort-icon" ng-show="sortKey=='Address'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span></th>  
  53. <th style="cursor: pointer; width: 100px;" ng-click="sort('JoiningDate')"><b>Joining Date</b> <span class="glyphicon sort-icon" ng-show="sortKey=='JoiningDate'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span></th>  
  54. <th style="cursor: pointer;" ng-click="sort('Department')"><b>Department</b> <span class="glyphicon sort-icon" ng-show="sortKey=='Department'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span></th>  
  55. <th style="cursor: pointer;" ng-click="sort('Designation')"><b>Designation</b> <span class="glyphicon sort-icon" ng-show="sortKey=='Designation'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span></th>  
  56.   
  57. <th><b>Actions</b></th>  
  58. </tr>  
  59. <tr dir-paginate="employee in employees|orderBy:sortKey:reverse|filter:search|itemsPerPage:10" ng-model="search">  
  60.   
  61. <td>{{employee.Id}}  
  62. </td>  
  63. <td>{{employee.name}}  
  64. </td>  
  65. <td style="width: 100px;">{{employee.DOB |date:'dd-MM-yyyy'}}  
  66. </td>  
  67. <td>{{employee.Gender}}  
  68. </td>  
  69. <td>{{employee.Email}}  
  70. </td>  
  71. <td>{{employee.Mobile}}  
  72. </td>  
  73. <td>{{employee.Address}}  
  74. </td>  
  75. <td style="width: 100px;">{{employee.JoiningDate}}  
  76. </td>  
  77. <td>{{employee.DepartmentName}}  
  78. </td>  
  79. <td>{{employee.DesignationName}}  
  80. </td>  
  81.   
  82. <td>  
  83. <a class="btn btn-Primary btn-sm" ng-click="editEmployee(employee)" href="">Edit</a>  
  84. </td>  
  85. </tr>  
  86. <b style="color: #5bc0de;">Total Records </b><b>{{employees.length}} </b>  
  87. </table>  
  88.   
  89. <dir-pagination-controls  
  90. max-size="10"  
  91. direction-links="true"  
  92. boundary-links="true">  
  93. </dir-pagination-controls>  
  94.   
  95. <div id="myModal" class="modal fade" role="dialog">  
  96. <div class="modal-dialog">  
  97.   
  98. <!-- Modal content-->  
  99. <div class="modal-content">  
  100. <div class="modal-header">  
  101. <button type="button" class="close" data-dismiss="modal">×</button>  
  102. <h4 class="modal-title">{{Action}} Employee Details</h4>  
  103. </div>  
  104. <div class="modal-body">  
  105. <div class="form-horizontal">  
  106. <div class="form-group">  
  107. <div class="row">  
  108. <div class="col-md-2 col-sm-2" style="margin-left: 20px; color: #5bc0de;">  
  109. <b>Name :</b>  
  110. </div>  
  111. <div class="col-md-8 col-sm-8">  
  112. <input type="text" class="form-control" data-modal="modal" ng-model="employeeName" placeholder="Employee's Name" ng-required="true" />  
  113. </div>  
  114. </div>  
  115. </div>  
  116. <div class="form-group">  
  117. <div class="row">  
  118. <div class="col-md-2 col-sm-2" style="margin-left: 20px; color: #5bc0de;">  
  119. <b>DOB :</b>  
  120. </div>  
  121. <div class="col-md-8 col-sm-8">  
  122. <div class="input-group date">  
  123. <input class="form-control" type="text" id="datetimepicker" value="1990/01/01">  
  124. <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>  
  125. </div>  
  126. </div>  
  127. </div>  
  128. </div>  
  129. <div class="form-group">  
  130. <div class="row">  
  131. <div class="col-md-2 col-sm-2" style="margin-left: 20px; color: #5bc0de;">  
  132. <b>Gender:</b>  
  133. </div>  
  134. <div class="col-md-8 col-sm-8" ng-required="true">  
  135. <input type="radio" title="Male" data-modal="modal" ng-model="employeeGender" value="Male" />  
  136. Male  
  137. <input type="radio" title="Female" data-modal="modal" ng-model="employeeGender" value="Female" />  
  138. Female  
  139. </div>  
  140. f
  141. </div>  
  142. </div>  
  143. <div class="form-group">  
  144. <div class="row">  
  145. <div class="col-md-2 col-sm-2" style="margin-left: 20px; color: #5bc0de;">  
  146. <b>Email:</b>  
  147. </div>  
  148. <div class="col-md-8 col-sm-8">  
  149. <input type="email" class="form-control" data-modal="modal" ng-model="employeeEmail" placeholder="Employee's Email" ng-required="true" />  
  150. </div>  
  151. </div>  
  152. </div>  
  153. <div class="form-group">  
  154. <div class="row">  
  155. <div class="col-md-2 col-sm-2" style="margin-left: 20px; color: #5bc0de;">  
  156. <b>Mobile:</b>  
  157. </div>  
  158. <div class="col-md-8 col-sm-8">  
  159. <input type="text" class="form-control" data-modal="modal" ng-model="employeeMobile" placeholder="Employee's Mobile" ng-required="true" />  
  160. </div>  
  161. </div>  
  162. </div>  
  163. <div class="form-group">  
  164. <div class="row">  
  165. <div class="col-md-2 col-sm-2" style="margin-left: 20px; color: #5bc0de;">  
  166. <b>Address:</b>  
  167. </div>  
  168. <div class="col-md-8 col-sm-8">  
  169. <input type="text" class="form-control" data-modal="modal" ng-model="employeeAddress" placeholder="Employee's Address" ng-required="true" />  
  170. </div>  
  171. </div>  
  172. </div>  
  173. <div class="form-group">  
  174. <div class="row">  
  175. <div class="col-md-2 col-sm-2" style="margin-left: 20px; color: #5bc0de;">  
  176. <b>Joining Date:</b>  
  177. </div>  
  178. <div class="col-md-8 col-sm-8">  
  179. <input type="date" class="form-control" data-modal="modal" ng-model="employeeJoiningDate" ng-required="true" />  
  180. </div>  
  181. </div>  
  182. </div>  
  183. <div class="form-group">  
  184. <div class="row">  
  185. <div class="col-md-2 col-sm-2" style="margin-left: 20px; color: #5bc0de;">  
  186. <b>Department:</b>  
  187. </div>  
  188. <div class="col-md-8 col-sm-8">  
  189. <select id="ddlDepartment" class="form-control" data-modal="modal" ng-model="employeeDepartment" ng-options="dep.Id as dep.DepartmentName for dep in departments" ng-required="true">  
  190. <option value="" disabled>--Select Department--</option>  
  191. @* <option data-ng-repeat="dep in departments" value="{{dep.Id}}">{{dep.DepartmentName}}</option>*@  
  192. </select>  
  193. </div>  
  194. </div>  
  195. </div>  
  196. <div class="form-group">  
  197. <div class="row">  
  198. <div class="col-md-2 col-sm-2" style="margin-left: 20px; color: #5bc0de;">  
  199. <b>Designation:</b>  
  200. </div>  
  201. <div class="col-md-8 col-sm-8">  
  202. <select id="ddlDesignation" class="form-control" data-modal="modal" ng-model="employeeDesignation" ng-options="dsg.Id as dsg.DesignationName for dsg in designations" ng-required="true">  
  203. <option value="" disabled>--Select Designation--</option>  f/span>
  204. </select>  
  205. </div>  
  206. </div>  
  207. </div>  
  208.   
  209. <div class="form-group">  
  210. <div class="row">  
  211. <div class="col-md-2 col-sm-2" style="margin-left: 20px; color: #5bc0de;"></div>  
  212. <div class="col-md-8 col-sm-8">  
  213. </div>  
  214. </div>  
  215. </div>  
  216. </div>  
  217.   
  218. <div class="modal-footer">  
  219. <input type="button" class="btnAdd btn btn-success" value="Save" ng-click="AddUpdateEmployee()" data-dismiss="modal" />  
  220. <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>  
  221. </div>  
  222.   
  223.   
  224. </div>  
  225. </div>  
  226. </div>  
  227. </div>  
  228.   
  229. <div id="alertModal" class="modal fade">  
  230. <div class="modal-dialog">  
  231. <div class="modal-content">  
  232. <!-- dialog body -->  
  233. <div class="modal-body">  
  234. <button type="button" class="close" data-dismiss="modal">×</button>  
  235. {{msg}}  
  236. </div>  
  237. <!-- dialog buttons -->  
  238. <div class="modal-footer">  
  239. <button type="button" ng-click="alertmsg()" class="btn btn-primary">OK</button>  
  240. </div>  
  241. </div>  
  242. </div>  
  243. </div>  
  244.   
  245.   
  246. </div>  
  247. </body>  
  248. </html>  
Starts with paging
  • Download DirPagination.js and save in the content folder of project.
  • Update the code in Module.js with given code.
  1. var app = angular.module("myApp", ['angularUtils.directives.dirPagination']);  
Apply CSS and Scripts file
  • Find BundleConfig.cs in App_Start folder.
  • Here we register the css snd js files to use with the layout page.
  1.  public static class BundleConfig  
  2. {  
  3. public static void RegisterBundles(BundleCollection bundles)  
  4. {  
  5. RegisterStyleBundles(bundles);  
  6. RegisterJavascriptBundles(bundles);  
  7. }  
  8.   
  9. private static void RegisterStyleBundles(BundleCollection bundles)  
  10. {  
  11. bundles.Add(new StyleBundle("~/css")  
  12. .Include("~/Content/bootstrap.css"
  13. .Include("~/Content/site.css"));  
  14. }  
  15.   
  16. private static void RegisterJavascriptBundles(BundleCollection bundles)  
  17. {  
  18. bundles.Add(new ScriptBundle("~/js")  
  19. .Include("~/Scripts/jquery-{version}.js")  
  20. .Include("~/Scripts/jquery-ui-{version}.js")  
  21. .Include("~/Scripts/bootstrap.js"));  
  22. }  
  23. }  
Starts writing code for CRUD operations
  •  In the EmployeeController,  AddEmployee method passed with Employee class is used to store the data in database.
  • This method returns the string message to the service.
  1. <-- Employee record insertion code -->  
  2. public string AddEmployee(Employee Emp)  
  3. {  
  4. if (Emp != null)  
  5. {  
  6. using (SahilEntities dataContext = new SahilEntities())  
  7. {  
  8. Employee employee = new Employee();  
  9. employee.name = Emp.name;  
  10. employee.DOB = Convert.ToDateTime(Emp.DOB).ToString("yyyy/MM/dd");  
  11. employee.Gender = Emp.Gender;  
  12. employee.Email = Emp.Email;  
  13. employee.Mobile = Emp.Mobile;  
  14. employee.Address = Emp.Address;  
  15. employee.JoiningDate = Convert.ToDateTime(Emp.JoiningDate).ToString("yyyy/MM/dd");  
  16. employee.DepartmentID = Emp.DepartmentID;  
  17. employee.DesignationID = Emp.DesignationID;  
  18. dataContext.Employees.Add(employee);  
  19. dataContext.SaveChanges();  
  20. return "Employee added Successfully";  
  21. }  
  22. }  
  23. else  
  24. {  
  25. return "Addition of Employee unsucessfull !";  
  26. }  
  27. }  
  • Here Empno is passed in the getEmployeeByNo is used to get the employee from employee Id.
  • This method returns the Json data to controller.js.
  1.  <-- Get Employee by ID -->  
  2. public JsonResult getEmployeeByNo(string EmpNo)  
  3. {  
  4. try  
  5. {  
  6. using (SahilEntities dataContext = new SahilEntities())  
  7. {  
  8. int no = Convert.ToInt32(EmpNo);  
  9. var employeeList = dataContext.Employees.Find(no);  
  10. return Json(employeeList, JsonRequestBehavior.AllowGet);  
  11. }  
  12. }  
  13. catch (Exception exp)  
  14. {  
  15. return Json("Error in getting record !", JsonRequestBehavior.AllowGet);  
  16. }  
  17.   
  18. }  
  • Update method update the employee data into the database and returns the response as a string message to the service.
  1.  <-- Employee record updation code -->  
  2. public string UpdateEmployee(Employee Emp)  
  3. {  
  4. if (Emp != null)  
  5. {  
  6. using (SahilEntities dataContext = new SahilEntities())  
  7. {  
  8. int no = Convert.ToInt32(Emp.Id);  
  9. var employeeList = dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();  
  10. employeeList.name = Emp.name;  
  11. employeeList.DOB = Convert.ToDateTime(Emp.DOB).ToString("yyyy/MM/dd");  
  12. employeeList.Gender = Emp.Gender;  
  13. employeeList.Email = Emp.Email;  
  14. employeeList.Mobile = Emp.Mobile;  
  15. employeeList.Address = Emp.Address;  
  16. employeeList.JoiningDate = Convert.ToDateTime(Emp.JoiningDate).ToString("yyyy/MM/dd");  
  17. employeeList.DepartmentID = Emp.DepartmentID;  
  18. employeeList.DesignationID = Emp.DesignationID;  
  19. dataContext.SaveChanges();  
  20. return "Employee Updated Successfully";  
  21. }  
  22. }  
  23. else  
  24. {  
  25. return "Invalid Employee";  
  26. }  
  27. }  
  • This method is used to bind the designation dropdownlist.This method returns data in Json to the service.
  1. <-- Bind dropdownlist of designations -->  
  2. public JsonResult GetDesignations()  
  3. {  
  4. using (SahilEntities context = new SahilEntities())  
  5. {  
  6. var desg = context.Designations.ToList();  
  7. return Json(desg, JsonRequestBehavior.AllowGet);  
  8. }  
  9. }   
  • This method is used to bind the department dropdownlist.This method returns data in Json to the service.
  1. <-- Bind dropdownlist of departments -->  
  2. public JsonResult GetDepartments()  
  3. {  
  4. using (SahilEntities data = new SahilEntities())  
  5. {  
  6. var deps = data.Departments.ToList();  
  7. return Json(deps, JsonRequestBehavior.AllowGet);  
  8. }  
  9. }   
Write code in Controller.js i.e. given below 
  • AddEmployeeDiv function basically calls the modal popup for adding employee information but some other functions also called on calling this function.
  • ClearFields function called in the same function are used to empty the html controls.
  • GetDepartments() and GetDesignations() calls the function for binding drop downs simultaneously.
  • alertmsg() close the alert popup that display the messages.
  • GetDesignations() calls the GetDesignations() method from the service to bind the dropdown.
  • The response returned in the data is passed to the $scope to access on the page.
  • GetDepartments() works same like GetDesignations.
  • editEmployee() function calls the function from the service and returned data is filled in every $scope to show on the page.
  • AddUpdateEmployee() insert and update the employee based on the action name.Here all the data from the $scopes is stored in the object named employee containing fields with the same name as in the database.
  • After this based on action name save or update function from the service is called.
  • In $scope.Action we store Add if we create new employee and store Edit if we edit the employee.
  • At last ClearFields() function clear the HTML controls after saving or updating the records.
  • Add the given code in Controller.js file.
  1. <-- This is used to open popup for adding record. -->  
  2.   
  3. $scope.AddEmployeeDiv = function () {  
  4. ClearFields();  
  5. $scope.Action = "Add";  
  6. GetDepartments();  
  7. GetDesignations();  
  8. }  
  9. <-- Alert Popup for save ,update messages . -->  
  10. $scope.alertmsg = function () {  
  11. $("#alertModal").modal('hide');  
  12. };  
  13.   
  14. <-- Bind dropdownlist for designation. -->  
  15.   
  16. function GetDesignations() {  
  17. var desg = myService.GetDesignations();  
  18.   
  19. desg.then(function (dsg) {  
  20. $scope.designations = dsg.data;  
  21. }, function (dsg) {  
  22. $("#alertModal").modal('show');  
  23. $scope.msg = "Error in filling designation drop down !";  
  24. });  
  25. }  
  26.   
  27. <-- Bind dropdownlist for department. -->  
  28. function GetDepartments() {  
  29. var departments = myService.GetDepartment();  
  30.   
  31. departments.then(function (dep) {  
  32. $scope.departments = dep.data;  
  33. }, function (dep) {  
  34. $("#alertModal").modal('show');  
  35. $scope.msg = "Error in filling departments drop down !";  
  36. });  
  37. }  
  38.   
  39. <-- Get the employee By ID. -->  
  40. $scope.editEmployee = function (employee) {  
  41. debugger;  
  42. GetDesignations();  
  43. GetDepartments();  
  44. var getData = myService.getEmployee(employee.Id);  
  45. getData.then(function (emp) {  
  46. $scope.employee = emp.data;  
  47. $scope.employeeId = employee.Id;  
  48. $scope.employeeName = employee.name;  
  49. $scope.employeeDOB = new Date(employee.DOB);  
  50. $scope.employeeGender = employee.Gender;  
  51. $scope.employeeEmail = employee.Email;  
  52. $scope.employeeMobile = employee.Mobile;  
  53. $scope.employeeAddress = employee.Address;  
  54. $scope.employeeJoiningDate = employee.JoiningDate;  
  55. $scope.employeeDepartment = employee.DepartmentID;  
  56. $scope.employeeDesignation = employee.DesignationID;  
  57. $scope.Action = "Edit";  
  58. $("#myModal").modal('show');  
  59. },  
  60. function (msg) {  
  61. $("#alertModal").modal('show');  
  62. $scope.msg = msg.data;  
  63. });  
  64. }  
  65.   
  66. <-- Insertion and updation code. -->  
  67. $scope.AddUpdateEmployee = function () {  
  68. var Employee = {  
  69. Name: $scope.employeeName,  
  70. DOB: $scope.employeeDOB,  
  71. Gender: $scope.employeeGender,  
  72. Email: $scope.employeeEmail,  
  73. Mobile: $scope.employeeMobile,  
  74. Address: $scope.employeeAddress,  
  75. JoiningDate: $scope.employeeJoiningDate,  
  76. DepartmentID: $scope.employeeDepartment,  
  77. DesignationID: $scope.employeeDesignation  
  78. };  
  79.   
  80. var getAction = $scope.Action;  
  81.   
  82. if (getAction == "Edit") {  
  83. Employee.Id = $scope.employeeId;  
  84. var getData = myService.updateEmp(Employee);  
  85. getData.then(function (msg) {  
  86. GetAllEmployee();  
  87. ClearFields();  
  88. $("#alertModal").modal('show');  
  89. $scope.msg = msg.data;  
  90. }, function (msg) {  
  91. $("#alertModal").modal('show');  
  92. $scope.msg = msg.data;  
  93. });  
  94. }  
  95. else {  
  96. var getData = myService.AddEmp(Employee);  
  97. getData.then(function (msg) {  
  98. GetAllEmployee();  
  99. $("#alertModal").modal('show');  
  100. $scope.msg = msg.data;  
  101. ClearFields();  
  102.   
  103. }, function (msg) {  
  104. $("#alertModal").modal('show');  
  105. $scope.msg = msg.data;  
  106. });  
  107. }  
  108. debugger;  
  109. GetAllEmployee();  
  110. $scope.refresh();  
  111. }  
  112.   
  113. <-- Clear fields after save -->  
  114.   
  115. function ClearFields() {  
  116. $scope.employeeId = "";  
  117. $scope.employeeName = "";  
  118. $scope.employeeDOB = "";  
  119. $scope.employeeGender = "";  
  120. $scope.employeeEmail = "";  
  121. $scope.employeeMobile = "";  
  122. $scope.employeeAddress = "";  
  123. $scope.employeeJoiningDate = "";  
  124. $scope.employeeDepartment = "";  
  125. $scope.employeeDesignation = "";  

Start writing code in Service.js 
  • AddEmp function calls the server method AddEmployee from EmployeeController by providing url,method,dataType,data.The response returned from the server is returned to the controller.js.
  • getEmployee function calls the getEmployeeByNo method from the Employee controller by providing url and employeeID as parameter.Again the response is passed to the controller.js.
  • updateEmp calls the UpdateEmployee method from the server and returns the response in same manner.
  • getDesignation calls GetDesignations from server to get the complete list of designations and fill the drop down list with that data.
  • Same process is with the getDepartments.
  • Add this code in the service.js file.
  1. <-- Calls Add Employee method on server -->  
  2. this.AddEmp = function (employee) {  
  3. var response = $http({  
  4. method: "post",  
  5. url: "/Employee/AddEmployee",  
  6. data: JSON.stringify(employee),  
  7. dataType: "json"  
  8. });  
  9. return response;  
  10. }  
  11.   
  12. <-- Calls get Employee By Id method on server -->  
  13. this.getEmployee = function (employeeID) {  
  14. var response = $http({  
  15. method: "post",  
  16. url: "/Employee/getEmployeeByNo",  
  17. params: {  
  18. id: JSON.stringify(employeeID)  
  19. }  
  20. });  
  21. return response;  
  22. }  
  23.   
  24. <--Calls the update method on server -->  
  25. this.updateEmp = function (employee) {  
  26. var response = $http({  
  27. method: "post",  
  28. url: "/Employee/UpdateEmployee",  
  29. data: JSON.stringify(employee),  
  30. dataType: "json"  
  31. });  
  32. return response;  
  33. }  
  34. <-- Calls the method on server for Designation dropdownlist -->  
  35. this.GetDesignations = function () {  
  36. return $http.get("/Employee/GetDesignations");  
  37. };  
  38.   
  39. <-- Calls the method on server for Department dropdownlist -->  
  40. this.GetDepartment = function () {  
  41. return $http.get("/Employee/GetDepartments");  
  42. };   
That's it with the code.
 
Read more articles on AngularJS:

Up Next
    Ebook Download
    View all
    Learn
    View all