Display Message When Filtering Records Not Found In AngularJS With ASP.NET MVC

Introduction
 
In most of the Web Applications, we display the records in a grid but sometimes a user wants to search the record based on the attribute value, which means a user wants to search all the records, based on the name. The fact is, if the record is not present in the current page, it needs to display "No records found". To implement it, we are going to use AngularJS filter concept to search the records in ASP.NET MVC.
 
Using Code
 
To implement filter functionality in AngularJS in ASP.NET MVC, below are steps: 
  1. Design a table which holds Employee information.
  2. Create a model class.
  3. Create an action which retrieves the data from an Employee table.
  4. In view, design table will render the employee records and search the fields.
  5. Send AJAX request to the Server to get the employees records and bind to the scope variable.  
Database Design
 
Let's design a table which keeps information about an employee. The SQL query, given below, is used to create table(tblEmployee) with the required columns ID like FirstName, LastName, Designation, Email and ReportID etc.
  1. CREATE TABLE [dbo].[tblEmployee](    
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,    
  3.     [FirstName] [varchar](50) NULL,    
  4.     [LastName] [varchar](50) NULL,    
  5.     [Designation] [varchar](50) NULL,    
  6.     [Email] [varchar](50) NULL,    
  7.     [Address] [varchar](maxNULL,    
  8.     [ReportID] [intNULL,    
  9.     [IsActive] [bitNULL,    
  10.  CONSTRAINT [PK_tblEmployee] PRIMARY KEY CLUSTERED     
  11. (    
  12.     [Id] ASC    
  13. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,   
  14.    ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]    
  15. ON [PRIMARY]   
Model
 
Add model(Employee.cs) is given below in Model folder with properties ID, first name, last, designation, Email, report ID etc.
  1. public class Employee  
  2. {  
  3.     public int Id { getset; }  
  4.     public string FirstName { getset; }  
  5.     public string LastName { getset; }  
  6.     public string Designation { getset; }  
  7.     public string Email { getset; }  
  8.     public bool IsActive { getset; }  
  9. }  
Controller
 
In Controller, add an action which retrieves the Employee records and returns the data in JSON format. Here, I have used simple ADO.NET to get the data. You can use EntityFramework, if you want.
  1. [HttpGet]  
  2. public JsonResult GetEmployees()  
  3. {  
  4.     List<Employee> empChartList = new List<Employee>();  
  5.   
  6.     string query = "SELECT Id, FirstName + ' ' + ISNULL(LastName, '') AS Name, Designation, Email, ReportID";  
  7.     query += " FROM tblEmployee";  
  8.     
  9.     // Get it from Web.config
  10.     string connetionString = "Data Source=Test-PC\\SQLEXPRESS;Initial Catalog=AllTest;Integrated Security=True;";  
  11.     using (SqlConnection con = new SqlConnection(connetionString))  
  12.     {  
  13.         using (SqlCommand cmd = new SqlCommand(query))  
  14.         {  
  15.             cmd.CommandType = CommandType.Text;  
  16.             cmd.Connection = con;  
  17.             con.Open();  
  18.             using (SqlDataReader dr = cmd.ExecuteReader())  
  19.             {  
  20.                 while (dr.Read())  
  21.                 {  
  22.                     empChartList.Add(new Employee()  
  23.                     {  
  24.                         Id = dr.GetInt32(0),  
  25.                         FirstName = dr.GetString(1),  
  26.                         Designation = dr.GetString(2),  
  27.                         Email = dr.GetString(3),  
  28.                         ReportID = dr.IsDBNull(4) ? 0 : dr.GetInt32(4)  
  29.                     });  
  30.                 }  
  31.             }  
  32.             con.Close();  
  33.         }  
  34.     }  
  35.   
  36.     return Json(empChartList, JsonRequestBehavior.AllowGet);  
  37. }     
View
 
It's time to design the View page to render the employee records and search fields. In the code given below, there is a DIV which helps to display the loading image when an AJAX request is sent to the Server. It contains another DIV, which holds search field and an employee table. In Employee grid table, it uses ng-repeat to loop over the records and creates new rows to display. It also implements AngularJS filter functionality, which means, when a user types name in the textbox, it displays the records with the matching name.
 
There is another DIV with ID notFoundDiv, which helps to display the message "Records not found", when there is no record from the Server or doesn't match with the search criteria. 
  1. <div ng-app="mvcApp" ng-controller="MyController">  

  2.     <button ng-click="myFunction()">Click to Load Data!</button>  
  3.     <div id="lodingDiv" ng-show="LoadingImg">  
  4.         <img src="~/Content/pageloader.gif" class="ajax-loader" />  
  5.         LOADING..  
  6.     </div>  

  7.     <div ng-show="EmpGridVisible">  
  8.         <table>  
  9.             <tr>  
  10.                 <td>Search by Name :</td>  
  11.                 <td colspan="2">  
  12.                     <input type="text" ng-model="empName" placeholder="Search">  
  13.                 </td>  
  14.             </tr>  
  15.         </table>          
  16.   
  17.         <table ng-show="(employees).length>0">  
  18.             <tr>  
  19.                 <th><a href="" ng-click="columnToOrder='Id';reverse=!reverse">ID</a></th>  
  20.   
  21.                 <th>  
  22.                     <a href="" ng-click="columnToOrder='FirstName';reverse=!reverse">Name</a>  
  23.                 </th>  
  24.                 <th>  
  25.                     <a href="" ng-click="columnToOrder='Designation';reverse=!reverse">Designation</a>  
  26.                 </th>  
  27.                 <th>  
  28.                     <a href="" ng-click="columnToOrder='Email';reverse=!reverse">Email</a>  
  29.                 </th>  
  30.             </tr>  
  31.             <tr ng-repeat="emp in employees| filter:{FirstName:empName} |orderBy:columnToOrder:reverse">  
  32.                 <td>{{emp.Id}}</td>  
  33.                 <td>{{emp.FirstName }}</td>  
  34.                 <td>{{emp.Designation }}</td>  
  35.                 <td>{{emp.Email ||'email not exist' }}</td>  
  36.             </tr>  
  37.         </table>  

  38.         <div id="notFoundDiv" ng-show="(employees|filter:empName).length==0" style="color: red; font-weight: bold">No Records Found</div>  
  39.         
  40.     </div>  
  41. </div>  
Next, we need to write the code for sending an AJAX request to the Server and get all the employees' data. In the code, given below, first we need to add AngularJS reference in our project. Secondly, we create a module with name as "mvcApp", which is injected to create controller named as "MyController".
 
Inside the controller, it hides LoadingImage, EmpGridVisible in the page load time and it displays, when button click happens to load the employees.
Afterwards, it creates a function myFunction, which calls on the button click to send AJAX to the Server and assign an employee data to employees scope variable.
  1. <script src="
    https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js
    "
    ></script>  

  2. <script>  
  3.     var angular = angular.module('mvcApp', []);  
  4.   
  5.     angular.controller('MyController'function ($scope, $http) {  
  6.         $scope.EmpGridVisible = false;  
  7.         $scope.LoadingImg = false;  
  8.   
  9.         $scope.myFunction = function () {  
  10.             $scope.EmpGridVisible true;  
  11.             $scope.LoadingImg = true;  
  12.   
  13.             // Sending AJAX request to server  
  14.             $http.get('/Home/GetEmployees').success(function (data) {  
  15.                 $scope.employees = data;  
  16.                 // Hiding loading image  
  17.                 $scope.LoadingImg = false;  
  18.             });  
  19.         }  
  20.     });  
  21. </script>  
Add the following style to make records appear in the designed way. It also contains style to display the loading image css, when an AJAX request goes to the Server. 
  1. <style>  
  2.     table {  
  3.         border-collapsecollapse;  
  4.         border-spacing0;  
  5.         width35%;  
  6.         display: table;  
  7.         text-aligncenter;  
  8.     }  
  9.   
  10.     .ng-binding {  
  11.         padding8px;  
  12.     }  
  13.   
  14.     a {  
  15.         text-decorationnone;  
  16.         colorwhite;  
  17.     }  
  18.   
  19.     th {  
  20.         background#0270bf;  
  21.     }  
  22.   
  23.     /*  Define the background color for all the EVEN background rows  */  
  24.     tr:nth-child(even) {  
  25.         background#f1f1f1;  
  26.     }  
  27.   
  28.     #mydiv {  
  29.         positionabsolute;  
  30.         top: 0;  
  31.         left: 0;  
  32.         width100%;  
  33.         height100%;  
  34.         z-index1000;  
  35.         background-color: grey;  
  36.         opacity: .8;  
  37.     }  
  38.   
  39.     .ajax-loader {  
  40.         positionabsolute;  
  41.         left: 50%;  
  42.         top: 50%;  
  43.         margin-left-32px/* -1 * image width / 2 */  
  44.         margin-top-32px/* -1 * image height / 2 */  
  45.         displayblock;  
  46.     }  
  47. </style>  
After implementing the code snippets, given above, browse your page and it looks, as shown in Figure 1 as an output. In Figure 1, it has 3 snapshots: 1 to display all the records without searching, 2 to display the records with search by Name "ma", 3 to display "Records not found", when name doesn't match with any any records.
 
Displays records based on search by name
Figure 1: Displays records, based on search by name
 
Conclusion
 
Here, we discussed displaying the records through sending an AJAX request, using AngularJS. How we can implement the filter functionality and display a message when a record is not found, is also discussed in this article.


Similar Articles