Learn MVC Using Angular Datatable

MVC

Introduction

In this article, we will learn MVC, using AngularJS data binding to the datatable from the Server side with the stored procedure, using Visual Studio 2015

Why use Angular Datatable?

Datatable is the most powerful table. It is best to load a large amount of data. The table is designed to be extremely flexible and lightweight.

Some main features are given below.

  • Column Reordering.
  • Column Resizing.
  • Handle Large Data.
  • Client Side & Server Side Pagination/Sorting.
  • Fixed And Fluid Height.

In this article, we are going to

  • Create a database.
  • Create a stored procedure.
  • Create MVC Application.
  • Using Angular Datatable.

Create a database

Open SQL Server 2016. Click New Query Window & run the query given below. 

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

Create a table

I will create a new table, which is based on the book information. 

  1. CREATE TABLE [dbo].[BookMaster](  
  2.     [BookCode] [varchar](10) NULL,  
  3.     [BookName] [varchar](50) NULL,  
  4.     [BookDesc] [varchar](500) NULL,  
  5.     [BookAuthor] [varchar](50) NULL  
  6. ON [PRIMARY]  
  7. GO   

After creating the table, add some data given below.

MVC

Create a stored procedure

I have written the stored procedure for my data operations, so run SP given below. In this procedure, I have done Select, Insert, Update & Delete. 

  1. Create PROCEDURE [dbo].[BookMaster_SP]  
  2. @BookCode   VARCHAR(10)=NULL,  
  3. @BookName   VARCHAR(50)=NULL,  
  4. @BookDesc   VARCHAR(500)=NUL,  
  5. @BookAutor  VARCHAR(500)=NULL,  
  6. @Mode       VARCHAR(50)  
  7. AS  
  8. BEGIN  
  9.     SET NOCOUNT ON;  
  10.   
  11.     IF (@Mode='ADD')  
  12.     BEGIN  
  13.         INSERT INTO BookMaster(BookCode,BookName,BookDesc,BookAuthor)  
  14.             VALUES(@BookCode,@BookName,@BookDesc,@BookAutor)  
  15.     END  
  16.   
  17.     IF (@Mode='EDIT')  
  18.     BEGIN  
  19.         UPDATE BookMaster SET BookName=@BookName,BookDesc=@BookDesc,BookAuthor=@BookAutor WHERE BookCode=@BookCode  
  20.               
  21.     END  
  22.   
  23.     IF (@Mode='DELETE')  
  24.     BEGIN  
  25.         DELETE FROM BookMaster WHERE BookCode=@BookCode  
  26.               
  27.     END  
  28.   
  29.     IF (@Mode='GET')  
  30.     BEGIN  
  31.         SELECT BookCode,BookName,BookDesc,BookAuthor FROM BookMaster  
  32.               
  33.     END  
  34.   
  35.     IF (@Mode='GETID')  
  36.     BEGIN  
  37.         SELECT BookCode,BookName,BookDesc,BookAuthor FROM BookMaster WHERE BookCode=@BookCode  
  38.               
  39.     END  
  40.   
  41.     SET NOCOUNT OFF;  
  42. END   

Create MVC Application

Open Visual Studio 2015, go to Menu New->New project ->select Visual C# under templates-> Choose ASP.NET Web Application.

MVC

Once you click OK button, one more Window opens. Select MVC.

MVC

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

Subsequently, inject datatable key word in Angular modular.

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

Create & design HTML page with the table. Mention datatable=ng. Now, bind the Server data.  

  1. <table datatable="ng" class="table-responsive table-bordered table-striped ">  
  2.   
  3.             <thead style="background-color:#428bca;color:white" >  
  4.                 <tr>  
  5.                     <td >  
  6.                         Book Code  
  7.                     </td>  
  8.                     <td >  
  9.                         Book Name  
  10.                     </td>  
  11.                     <td >  
  12.                         Book Description  
  13.                     </td>  
  14.                     <td>  
  15.                         Book Author Name  
  16.                     </td>  
  17.                     <td>  
  18.                         <span class="glyphicon glyphicon-edit"></span>  
  19.                     </td>  
  20.                     <td>  
  21.                         <span class="glyphicon glyphicon-trash"></span>  
  22.                     </td>  
  23.                 </tr>  
  24.             </thead>  
  25.   
  26.             <tbody>  
  27.                 <tr ng-repeat="model in LoadData">  
  28.                       
  29.                     <td >{{ model.BookCode }}</td>  
  30.                     <td >{{ model.BookName }}</td>  
  31.                     <td>{{ model.BookDesc }}</td>  
  32.                     <td>{{ model.BookAuthor }}</td>  
  33.                     <td><span class="glyphicon glyphicon-edit" ng-click="LoadById(model)"></span></td>  
  34.                     <td><span class="glyphicon glyphicon-trash" ng-click="DaleteById(model)"></span></td>  
  35.                 </tr>  
  36.             </tbody>  
  37.   
  38.         </table>   

Using Angular Datatable

Create Model folder in Solution Explorer & create new class in Model folder. 

  1. public class BookModel  
  2.     {  
  3.         public string BookCode { get; set; }  
  4.         public string BookName { get; set; }  
  5.         public string BookDesc{ get; set; }  
  6.         public string BookAuthor { get; set; }  
  7.         public string Mode { get; set; }  
  8.     }   

Write the method given below in home controller. LoadData displays the data in the Datatable & another one is using data manipulation. 

  1. [HttpPost]  
  2.  
  3.         #region LoadData  
  4.         public JsonResult LoadData(BookModel Param)  
  5.         {  
  6.             List<BookModel> BookList = new List<BookModel>();  
  7.             using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbSqlCon"].ConnectionString))  
  8.             {  
  9.                 var cmd = new SqlCommand("BookMaster_SP", con);  
  10.                 cmd.CommandType = CommandType.StoredProcedure;  
  11.                 cmd.Parameters.Add(new SqlParameter("@Mode", SqlDbType.VarChar)).Value = Param.Mode;  
  12.                 cmd.Parameters.Add(new SqlParameter("@BookCode", SqlDbType.VarChar)).Value = Param.BookCode;  
  13.                 try  
  14.                 {  
  15.                    con.Open();  
  16.                     using (SqlDataReader DbReader = cmd.ExecuteReader())  
  17.                         if (DbReader.HasRows)  
  18.                         {  
  19.                             while (DbReader.Read())  
  20.                             {  
  21.                                 BookModel Books = new BookModel();  
  22.                                 Books.BookCode = DbReader.GetString(DbReader.GetOrdinal("BookCode"));  
  23.                                 Books.BookName = DbReader.GetString(DbReader.GetOrdinal("BookName"));  
  24.                                 Books.BookDesc = DbReader.GetString(DbReader.GetOrdinal("BookDesc"));  
  25.                                 Books.BookAuthor = DbReader.GetString(DbReader.GetOrdinal("BookAuthor"));  
  26.                                 BookList.Add(Books);  
  27.                             }  
  28.                         }  
  29.                     return Json(BookList, JsonRequestBehavior.AllowGet);  
  30.                 }  
  31.                 finally  
  32.                 {  
  33.                         con.Close();  
  34.                 }  
  35.             }  
  36.         }  
  37.         #endregion  
  38.   
  39.         [HttpPost]  
  40.         #region EditData  
  41.         public string EditData(BookModel Param)  
  42.         {  
  43.             if (Param != null)  
  44.             {  
  45.                 using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbSqlCon"].ConnectionString))  
  46.                 {  
  47.                     var cmd = new SqlCommand("BookMaster_SP", con);  
  48.                     cmd.CommandType = CommandType.StoredProcedure;  
  49.                     cmd.Parameters.Add(new SqlParameter("@Mode", SqlDbType.VarChar)).Value = Param.Mode;  
  50.                     cmd.Parameters.Add(new SqlParameter("@BookCode", SqlDbType.VarChar)).Value = Param.BookCode;  
  51.                     cmd.Parameters.Add(new SqlParameter("@BookName", SqlDbType.VarChar)).Value = Param.BookName;  
  52.                     cmd.Parameters.Add(new SqlParameter("@BookDesc", SqlDbType.VarChar)).Value = Param.BookDesc;  
  53.                     cmd.Parameters.Add(new SqlParameter("@BookAutor", SqlDbType.VarChar)).Value = Param.BookAuthor;  
  54.                       
  55.                     try  
  56.                     {  
  57.                         con.Open();  
  58.                         cmd.ExecuteNonQuery();  
  59.                         return "Success";  
  60.                     }  
  61.                     catch (Exception ex)  
  62.                     {  
  63.                         return ex.ToString();  
  64.                     }  
  65.                     finally  
  66.                     {  
  67.                         if (con.State != ConnectionState.Closed)  
  68.                             con.Close();  
  69.   
  70.                     }  
  71.   
  72.                 }  
  73.             }  
  74.   
  75.             else  
  76.             {  
  77.                 return "Model Error";  
  78.             }  
  79.         }  
  80.         #endregion   

Declare the connection string in Web.config file. 

  1. <connectionStrings>  
  2.     <add name="DbSqlCon" connectionString="Data Source=xxxx; Initial Catalog=test; User Id=sa; Password=XXX; connect timeout=0;" providerName="System.Data.SqlClient;" />  
  3.   </connectionStrings>   

Create an Angular Controller & Service to get the data from the Server side.

Controller 

  1. $scope.LoadById = function (model)  
  2.     {  
  3.         $scope.Ed = model;  
  4.         $scope.Datamode = 'Update';  
  5.         $scope.Enable = true;  
  6.     }  
  7.   
  8.     $scope.Save = function ()  
  9.     {  
  10.         if ($scope.Datamode === 'Update')  
  11.         {  
  12.             var Param = {  
  13.                 Mode: 'EDIT',  
  14.                 BookCode: $scope.Ed.BookCode,  
  15.                 BookName: $scope.Ed.BookName,  
  16.                 BookDesc: $scope.Ed.BookDesc,  
  17.                 BookAuthor: $scope.Ed.BookAuthor  
  18.             }  
  19.         }  
  20.           
  21.         else  
  22.         {  
  23.             var Param = {  
  24.                 Mode: 'ADD',  
  25.                 BookCode: $scope.Ed.BookCode,  
  26.                 BookName: $scope.Ed.BookName,  
  27.                 BookDesc: $scope.Ed.BookDesc,  
  28.                 BookAuthor: $scope.Ed.BookAuthor  
  29.             }  
  30.         }  
  31.         var ServiceData = BookService.EditData(Param);  
  32.         ServiceData.then(function (result) {  
  33.             $scope.loadTable()  
  34.             $scope.Ed = '';           
  35.             $scope.message = "Data Save Successfully";  
  36.         }, function () {  
  37.   
  38.         });  
  39.     }  
  40.   
  41.     $scope.DaleteById = function (model) {  
  42.         var Param = {  
  43.             Mode: 'DELETE',  
  44.             BookCode: model.BookCode,  
  45.         }  
  46.         var ServiceData = BookService.EditData(Param);  
  47.         ServiceData.then(function (result) {  
  48.             $scope.loadTable()  
  49.             $scope.Ed = '';  
  50.             $scope.message = "Data Delete Successfully";  
  51.         }, function () {  
  52.   
  53.         });   

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.     }  
  10.   
  11.     this.EditData = function (Param) {  
  12.         var response = $http({  
  13.             method: "post",  
  14.             url: "Home/EditData",  
  15.             data: JSON.stringify(Param),  
  16.             dataType: "json"  
  17.         });  
  18.         return response;  
  19.     }   

Do not forget to refer the plug in files and JS file also.

Plug In 

  1. <link href="~/Plugin/datatables/media/css/jquery.dataTables.min.css" rel="stylesheet" />  
  2. <script src="~/Plugin/datatables/media/js/jquery.dataTables.js"></script>  
  3. <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/BookController.js"></script>   

Once you are done with the process given above, your datatable is ready to load. Thus, run the Application.

Output

MVC

Here, I have done simple data manipulation method.

Kindly refer my AngularJS articles

Conclusion

In this article, we have learnt MVC, using Angular datatable. If you have any queries, please tell me through the comments section.

Up Next
    Ebook Download
    View all
    Learn
    View all