MVC

Introduction

In this article, we will learn MVC using Angular data binding for dynamic control in datatable from server side Web API using visual studio 2017

In this article we are going to

Create Database

Open SQL Server 2016, Then Click “New Query” window & Run the below query.

  1. USE [master]
  2. GO
  3. CREATE DATABASE [test]
  4. CONTAINMENT = NONE
  5. ON PRIMARY
  6. ( NAME = N'test', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\test.mdf' , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB ),
  7. FILEGROUP [DocFiles] CONTAINS FILESTREAM DEFAULT
  8. ( NAME = N'FileStream', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\FileStream' , MAXSIZE = UNLIMITED)
  9. LOG ON
  10. ( NAME = N'test_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\test_log.ldf' , SIZE = 8192KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )
  11. GO
  12. ALTER DATABASE [test] SET COMPATIBILITY_LEVEL = 130
  13. GO
  14. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
  15. begin
  16. EXEC [test].[dbo].[sp_fulltext_database] @action = 'enable'
  17. end
  18. GO
  19. ALTER DATABASE [test] SET ANSI_NULL_DEFAULT OFF
  20. GO
  21. ALTER DATABASE [test] SET ANSI_NULLS OFF
  22. GO
  23. ALTER DATABASE [test] SET ANSI_PADDING OFF
  24. GO
  25. ALTER DATABASE [test] SET ANSI_WARNINGS OFF
  26. GO
  27. ALTER DATABASE [test] SET ARITHABORT OFF
  28. GO
  29. ALTER DATABASE [test] SET AUTO_CLOSE OFF
  30. GO
  31. ALTER DATABASE [test] SET AUTO_SHRINK OFF
  32. GO
  33. ALTER DATABASE [test] SET AUTO_UPDATE_STATISTICS ON
  34. GO
  35. ALTER DATABASE [test] SET CURSOR_CLOSE_ON_COMMIT OFF
  36. GO
  37. ALTER DATABASE [test] SET CURSOR_DEFAULT GLOBAL
  38. GO
  39. ALTER DATABASE [test] SET CONCAT_NULL_YIELDS_NULL OFF
  40. GO
  41. ALTER DATABASE [test] SET NUMERIC_ROUNDABORT OFF
  42. GO
  43. ALTER DATABASE [test] SET QUOTED_IDENTIFIER OFF
  44. GO
  45. ALTER DATABASE [test] SET RECURSIVE_TRIGGERS OFF
  46. GO
  47. ALTER DATABASE [test] SET DISABLE_BROKER
  48. GO
  49. ALTER DATABASE [test] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
  50. GO
  51. ALTER DATABASE [test] SET DATE_CORRELATION_OPTIMIZATION OFF
  52. GO
  53. ALTER DATABASE [test] SET TRUSTWORTHY OFF
  54. GO
  55. ALTER DATABASE [test] SET ALLOW_SNAPSHOT_ISOLATION OFF
  56. GO
  57. ALTER DATABASE [test] SET PARAMETERIZATION SIMPLE
  58. GO
  59. ALTER DATABASE [test] SET READ_COMMITTED_SNAPSHOT OFF
  60. GO
  61. ALTER DATABASE [test] SET HONOR_BROKER_PRIORITY OFF
  62. GO
  63. ALTER DATABASE [test] SET RECOVERY FULL
  64. GO
  65. ALTER DATABASE [test] SET MULTI_USER
  66. GO
  67. ALTER DATABASE [test] SET PAGE_VERIFY CHECKSUM
  68. GO
  69. ALTER DATABASE [test] SET DB_CHAINING OFF
  70. GO
  71. ALTER DATABASE [test] SET FILESTREAM( NON_TRANSACTED_ACCESS = FULL, DIRECTORY_NAME = N'DocFileDirctory' )
  72. GO
  73. ALTER DATABASE [test] SET TARGET_RECOVERY_TIME = 60 SECONDS
  74. GO
  75. ALTER DATABASE [test] SET DELAYED_DURABILITY = DISABLED
  76. GO
  77. EXEC sys.sp_db_vardecimal_storage_format N'test', N'ON'
  78. GO
  79. ALTER DATABASE [test] SET QUERY_STORE = OFF
  80. GO

Create Table

I will create a new table based on employee info.

  1. CREATE TABLE [dbo].[EmpMaster](
  2. [Row_id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
  3. [Emp_Code] [varchar](10) NULL,
  4. [Emp_FName] [varchar](50) NULL,
  5. [Emp_LName] [varchar](50) NULL,
  6. [Emp_Status] [bit] NULL,
  7. [Emp_DOB] [datetime] NULL,
  8. [Emp_Maritalstatus] [varchar](10) NULL,
  9. [Emp_Role] [varchar](50) NULL,
  10. [Emp_Department] [varchar](50) NULL,
  11. [Emp_Address] [varchar](500) NULL,
  12. [Emp_Profilestatus] [int] NULL,
  13. [Emp_Expriance] [int] NULL,
  14. [Create_By] [varchar](50) NULL,
  15. [Create_Date] [datetime] NULL
  16. ) ON [PRIMARY]

After creating the table add some data

  1. SET IDENTITY_INSERT [dbo].[EmpMaster] ON
  2. GO
  3. INSERT [dbo].[EmpMaster] ([Row_id], [Emp_Code], [Emp_FName], [Emp_LName], [Emp_Status], [Emp_DOB], [Emp_Maritalstatus], [Emp_Role], [Emp_Department], [Emp_Address], [Emp_Profilestatus], [Emp_Expriance], [Create_By], [Create_Date]) VALUES (CAST(1 AS Numeric(18, 0)), N'1000', N'Amit ', N'Sharma', 1, CAST(N'1958-04-20T00:00:00.000' AS DateTime), N'Married', N'Admin', N'Dev', N'California', 100, 20, N'Thiru', CAST(N'2017-07-24T00:00:00.000' AS DateTime))
  4. GO
  5. INSERT [dbo].[EmpMaster] ([Row_id], [Emp_Code], [Emp_FName], [Emp_LName], [Emp_Status], [Emp_DOB], [Emp_Maritalstatus], [Emp_Role], [Emp_Department], [Emp_Address], [Emp_Profilestatus], [Emp_Expriance], [Create_By], [Create_Date]) VALUES (CAST(2 AS Numeric(18, 0)), N'2000', N'Erik ', N'Dietrich', 0, CAST(N'1988-05-10T00:00:00.000' AS DateTime), N'Married', N'Employee', N'Dev', N'Washington', 50, 10, N'Thiru', CAST(N'2017-07-24T00:00:00.000' AS DateTime))
  6. GO
  7. INSERT [dbo].[EmpMaster] ([Row_id], [Emp_Code], [Emp_FName], [Emp_LName], [Emp_Status], [Emp_DOB], [Emp_Maritalstatus], [Emp_Role], [Emp_Department], [Emp_Address], [Emp_Profilestatus], [Emp_Expriance], [Create_By], [Create_Date]) VALUES (CAST(3 AS Numeric(18, 0)), N'3000', N'Abdul ', N'Azeez', 1, CAST(N'1990-02-14T00:00:00.000' AS DateTime), N'UnMarried', N'Employee', N'Dev', N'Michigan', 80, 8, N'Thiru', CAST(N'2017-07-24T00:00:00.000' AS DateTime))
  8. GO
  9. INSERT [dbo].[EmpMaster] ([Row_id], [Emp_Code], [Emp_FName], [Emp_LName], [Emp_Status], [Emp_DOB], [Emp_Maritalstatus], [Emp_Role], [Emp_Department], [Emp_Address], [Emp_Profilestatus], [Emp_Expriance], [Create_By], [Create_Date]) VALUES (CAST(4 AS Numeric(18, 0)), N'4000', N'Dizzy', N'Dee', 1, CAST(N'1995-01-10T00:00:00.000' AS DateTime), N'UnMarried', N'Employee', N'Test', N'Kentucky', 90, 5, N'Thiru', CAST(N'2017-07-24T00:00:00.000' AS DateTime))
  10. GO
  11. INSERT [dbo].[EmpMaster] ([Row_id], [Emp_Code], [Emp_FName], [Emp_LName], [Emp_Status], [Emp_DOB], [Emp_Maritalstatus], [Emp_Role], [Emp_Department], [Emp_Address], [Emp_Profilestatus], [Emp_Expriance], [Create_By], [Create_Date]) VALUES (CAST(5 AS Numeric(18, 0)), N'5000', N'John ', N'Sonmez ', 1, CAST(N'1989-05-10T00:00:00.000' AS DateTime), N'Married', N'Employee', N'Test', N'North Carolina', 0, 2, N'Thiru', CAST(N'2017-07-24T00:00:00.000' AS DateTime))
  12. GO

Create Store procedure

I have written the store procedure for my data operations so run the below SP. In this procedure, I have gathered different data for dynamic control

  1. CREATE PROCEDURE [dbo].[PC_EmpMaster]
  2. @Row_id BIGINT=NULL,
  3. @MODE VARCHAR(10)=NULL
  4. AS
  5. BEGIN
  6. SET NOCOUNT ON;
  7. IF(@MODE ='GET')
  8. BEGIN SELECT Row_id,Emp_Code,Emp_FName,Emp_LName,Emp_Status,CONVERT(VARCHAR(10), CONVERT( DATE ,Emp_DOB)) AS Emp_DOB,Emp_Maritalstatus,Emp_Profilestatus,Emp_Expriance,Emp_Address,Create_By,Create_Date AS Create_Date FROM EmpMaster
  9. END
  10. ELSE IF(@MODE ='GETBYID')
  11. BEGIN
  12. SELECT Emp_Code,Emp_FName,Emp_LName,Emp_Role,Emp_Department,Emp_Address FROM EmpMaster WHERE Row_id=@Row_id
  13. END
  14. SET NOCOUNT OFF;
  15. END

Open Visual Studio 2017

MVC

Go to New menu >Click New & project. Now it will open New Project Window

MVC

You can select ASP.NET Web Application on Framework 4.5. Enter the name of project in “Solution name” textbox then click ok button.

MVC

One more Window should appear. Select MVC Template in this popup & Click ok button.

After creating project click the below link you can download plug in files.

Then inject “datatable” key word in Angular modular

  1. angular.module('uiroute',['ui.router', 'datatables']);

Create & design HTML page with Table, in there mention as “datatable="ng".Then Binding the Server data

  1. <table datatable="ng" class="table-responsive table-bordered table-striped ">
  2. <thead style="background :rgb(142, 28, 123); color: white;">
  3. <tr>
  4. <th>
  5. </th>
  6. <th >
  7. Row ID #
  8. </th>
  9. <th >
  10. Employee Code
  11. </th>
  12. <th >
  13. Employee Name
  14. </th>
  15. <th >
  16. Date of Birth
  17. </th>
  18. <th >
  19. Marital Status
  20. </th>
  21. <th >
  22. Total Exprience
  23. </th>
  24. <th >
  25. Profile Status
  26. </th>
  27. <th >
  28. Employee Status
  29. </th>
  30. <th >
  31. Employee Address
  32. </th>
  33. <th>
  34. Created By
  35. </th>
  36. <th>
  37. Created Date
  38. </th>
  39. </tr>
  40. </thead>
  41. <tbody>
  42. <tr ng-repeat-start="Grid in LoadData" style="cursor:pointer">
  43. <td style="width:1% !important">
  44. <input type="checkbox" ng-model="Grid.isChecked" id="chk1_{{$index}}">
  45. <label for="chk1_{{$index}}"></label>
  46. <div style="display:none"></div>
  47. </td>
  48. <td>
  49. {{Grid.Row_id}}
  50. </td>
  51. <td class="SubGrid">
  52. {{Grid.Emp_Code}} <span ng-click="SubGrid(Grid.Row_id,$index)" class="caret"></span>
  53. </td>
  54. <td>{{Grid.Emp_FName}} {{Grid.Emp_LName}} </td>
  55. <td>{{Grid.Emp_DOB}}</td>
  56. <td align="center">
  57. <span class="label label-success" ng-show="Grid.Emp_Maritalstatus === 'UnMarried'">{{Grid.Emp_Maritalstatus}}</span>
  58. <span class="label label-info" ng-show="Grid.Emp_Maritalstatus !== 'UnMarried'">{{Grid.Emp_Maritalstatus}}</span>
  59. </td>
  60. <td>
  61. <span class="label label-danger">{{Grid.Emp_Expriance}}</span>
  62. </td>
  63. <td>{{Grid.Emp_Profilestatus}}
  64. <div class="c100 p{{Grid.Emp_Profilestatus}} blue small">
  65. <span>{{Grid.Emp_Profilestatus}} %</span>
  66. <div class="slice">
  67. <div class="bar"></div>
  68. <div class="fill"></div>
  69. </div>
  70. </div>
  71. <i class="glyphicon glyphicon-ok " style="color:green" ng-show="Grid.Emp_Profilestatus ===100"></i>
  72. <i class="glyphicon glyphicon-remove" style="color:red" ng-show="Grid.Emp_Profilestatus < 100"></i>
  73. </td>
  74. <td>
  75. <input type="checkbox" ng-model="Grid.Emp_Status" id="chk1_{{$index}}">
  76. <label for="chk1_{{$index}}"></label>
  77. <div style="display:none"></div>
  78. </td>
  79. <td>
  80. <input type="text" class="control-label" ng-disabled="!Grid.Emp_Status" ng-model="Grid.Emp_Address"/>
  81. </td>
  82. <td>{{Grid.Create_By}}</td>
  83. <td>{{Grid.Create_Date }}</td>
  84. </tr>
  85. <tr ng-show="ShowGrid==={{$index}}" ng-repeat-end>
  86. <td></td>
  87. <td colspan="6">
  88. <div class="col-sm-1"></div>
  89. <div class="col-lg-11" style=" border: 1px solid #e1e1e1;">
  90. <table class="table table-hover" style="padding-top:5px">
  91. <thead style="background-color: #563cbc;color:white;">
  92. <tr>
  93. <th style="width: 150px;background-color: #563cbc;color:white; ">
  94. First Name
  95. </th>
  96. <th style="width: 150px; background-color: #563cbc;color:white;">
  97. Last Name
  98. </th>
  99. <th style="width: 150px; background-color: #563cbc;color:white;">
  100. Department
  101. </th>
  102. <th style="width: 150px;background-color: #563cbc;color:white; ">
  103. Role
  104. </th>
  105. </tr>
  106. </thead>
  107. <tbody style="height: 150px !important;">
  108. <tr ng-repeat="SG in SubGrid">
  109. <td style="width: 150px;">{{SG.Emp_FName}}</td>
  110. <td style="width: 150px;">{{SG.Emp_LName}}</td>
  111. <td style="width: 150px;">{{SG.Emp_Department}}</td>
  112. <td style="width: 150px;">{{SG.Emp_Role}}</td>
  113. </tr>
  114. </tbody>
  115. </table>
  116. </div>
  117. </td>
  118. </tr>
  119. </tbody>
  120. </table>

Using Angular Datatable

Create “Model” folder in solution explorer & create new class in model folder.

  1. public class ParamModel
  2. {
  3. public string Mode { get; set; }
  4. public long Row_id { get; set; }
  5. }

Write below method in home controller. ”LoadData” displays the data in datatable.

  1. [HttpPost]
  2. #region LoadData
  3. public async Task<JsonResult> LoadData(BookModel Param)
  4. {
  5. var result = await Task.Run(() =>
  6. {
  7. try
  8. {
  9. HttpResponseMessage response = HttpClient.PostAsJsonAsync(apiUrl + "/GetEmployeeDetails", Param).Result;
  10. if (response.IsSuccessStatusCode)
  11. {
  12. var responseData = response.Content.ReadAsStringAsync().Result;
  13. return Json(responseData, JsonRequestBehavior.AllowGet);
  14. }
  15. else
  16. {
  17. return Json("Error", JsonRequestBehavior.AllowGet);
  18. }
  19. }
  20. catch (Exception ex)
  21. {
  22. return Json("Error" + ex.ToString(), JsonRequestBehavior.AllowGet);
  23. }
  24. });
  25. return result;
  26. }
  27. #endregion

In this method, I have called Web API function with async Method. My previous articles “Learn Web API Using SQL Helper Class” will help you learn how to create & consume web APIs. So just, refer to the API URL like below in Web.config file

  1. <add key="APIUrl" value="http://localhost:53490/api" />

Create an angular controller & service for getting data from server side.

Angular Controller

  1. $scope.loadTable = function () {
  2. var Param={
  3. Mode:'GET'
  4. }
  5. var ServiceData = BookService.loadGrid(Param);
  6. ServiceData.then(function (response) {
  7. var result = JSON.parse(response.data);
  8. $scope.LoadData = result.loadEmployeeList;
  9. }, function () {
  10. });
  11. }
  12. $scope.loadTable();
  13. $scope.LoadById = function (Row_id)
  14. {
  15. var Param = {
  16. Row_id: Row_id,
  17. Mode: 'GETBYID'
  18. }
  19. var ServiceData = BookService.loadGrid(Param);
  20. ServiceData.then(function (response) {
  21. var result = JSON.parse(response.data);
  22. $scope.SubGrid = result.loadEmployeeList;
  23. }, function () {
  24. });
  25. }
  26. $scope.SubGrid = function (Row_id,index)
  27. {
  28. if ($scope.ShowGrid == index) {
  29. $scope.ShowGrid = -1;
  30. $scope.SubGrid = {};
  31. } else {
  32. $scope.ShowGrid = index;
  33. $scope.LoadById(Row_id);
  34. }
  35. }

Angular Service

  1. this.loadGrid = function (Param) {
  2. var response = $http({
  3. method: "post",
  4. url: "Home/LoadData",
  5. data: JSON.stringify(Param),
  6. dataType: "json"
  7. });
  8. return response;
  9. }

Do not forget to refer to the plug in files, in the same way as the JS file .

Plug In

  1. <script src="~/Plugin/jQuery/jquery-2.2.3.min.js"></script>
  2. <script src="~/Plugin/datatables/media/js/jquery.dataTables.js"></script>
  3. <script src="~/Plugin/angular/angular.min.js"></script>
  4. <script src="~/Plugin/angular-ui-router/release/angular-ui-router.min.js"></script>
  5. <script src="~/Plugin/angular-datatables/dist/angular-datatables.js"></script>

My Files

  1. <script src="~/App/App.module.js"></script>
  2. <script src="~/App/App.config.js"></script>
  3. <script src="~/App/EmpController.js"></script>

Once you have finished the above process now your datatable is ready to load, so run the application.

Output 1

MVC

If you click Employee Code near Arrow Button, It will open Sub table also.

Output 2

MVC

See my pervious Angular JS Articles

Conclusion

In this article, we have learned about MVC using dynamic control datatable. If you have any queries, please tell me through the comments section because your comments are very valuable.

Happy Coding!...