Dynamic Checkbox Functionality Using Angular In ASP.NET MVC

Introduction
 
AngularJS is an MVC based framework. Google developed AngularJS. AngularJS is an open source project, which can be freely used, modified, and shared by others.
 
To know more, click here>> 
 
Description
 
Here, I will show you how checkbox works dynamically in drop-down list using AngularJS in ASP.NET MVC. Multiselect dropdown with checkboxes is used to use a dropdown like a feature that can select multiple values.
 
Source Code
 
 
Steps to build this project
 
Step 1
 
Create a table named "Menu".
 
T-SQL script for the table
  1. CREATE TABLE [dbo].[Menu] (  
  2.     [MenuID]   INT          NOT NULL,  
  3.     [MenuName] VARCHAR (50) NOT NULL,  
  4.     CONSTRAINT [PK_Menu] PRIMARY KEY CLUSTERED ([MenuID] ASC)  
  5. ); 
Then, a stored procedure is created to use this table.
 
Script for the stored procedure
  1. Create Procedure Sp_Menu  
  2. As  
  3. Begin  
  4. Select * From Menu  
  5. End 
  1. exec Sp_Menu 
 Add dummy records to the table.
 
 
 
Step 2
 
Create an ASP.NET MVC application named "SatyaCheckboxAngularjs".
 
Step 3
  • Go to Solution Explorer.
  • Right-click on Project name and click Add > New item > select ADO.net Entity Data Model under data > Enter model name > Add.
  • A popup window will appear (Entity Data Model Wizard). Select "Generate from database" > Next.
  • Choose your data connection > select database > Next.
  • Select table, i.e., Menu > enter Model Namespace > Finish. 
After the above steps, add the stored procedure using the steps mentioned in my another article Go here>>.
 
Step 4
 
Create a JavaScript file to get the Angular feature.
  • Here, I have created a folder named "Scripts" first.
  • Then, I have added a JS file for adding Angular components (module, controller etc).
  • Here, we will fetch the menu data from the database.
  • Right-click on your solution file (from Solution Explorer) and  Add > New Folder. Rename your folder.
  • Right click on your folder (Scripts) > Add > New Item > select "javascript" file > Enter name (here "MyApp.js")> OK. 
Code Ref
  1. var app = angular.module('MyApp', ['angularjs-dropdown-multiselect']);  
  2. app.controller('multiselectdropdown', ['$scope''$http'function ($scope, $http) {  
  3.       
  4.     $scope.MenusSelected = [];  
  5.     $scope.Menus = [];  
  6.     $scope.dropdownSetting = {  
  7.         scrollable: true,  
  8.         scrollableHeight: '200px'  
  9.     }  
  10.       
  11.     $http.get('/home/getmenus').then(function (data) {  
  12.         angular.forEach(data.data, function (value, index) {  
  13.             $scope.Menus.push({ id: value.MenuID, label: value.MenuName });  
  14.         });  
  15.     })  
  16.      
  17.     $scope.SubmittedMenus = [];  
  18.     $scope.SubmitData = function () {  
  19.         var menuIds = [];  
  20.         angular.forEach($scope.MenusSelected, function (value, index) {  
  21.             menuIds.push(value.id);  
  22.         });  
  23.   
  24.         var data = {  
  25.             menuIds: menuIds  
  26.         };  
  27.   
  28.         $http({  
  29.             method: "POST",  
  30.             url: "/home/savedata",  
  31.             data: JSON.stringify(data)  
  32.         }).then(function (data) {  
  33.             $scope.SubmittedMenus = data.data;  
  34.         }, function (error) {  
  35.             alert('Check Your Server Running Or Not!');  
  36.         })  
  37.     }  
  38. }]) 
Code Description
 
I have used an Angular directive named angularjs-dropdown-multiselect. This directive gives us a Bootstrap drop-down with the power of AngularJS directives. It's very easy to implement and has lots of features with functionality. It is used for using ng-dropdown-multiselect directive for getting multiselect dropdown with checkboxes.
  1. var app = angular.module('MyApp', ['angularjs-dropdown-multiselect']); 
Then, define the object with dropdown records scrollable or not and height.
  1. app.controller('multiselectdropdown', ['$scope''$http'function ($scope, $http) {  
  2.     $scope.MenusSelected = [];  
  3.     $scope.Menus = [];  
  4.     $scope.dropdownSetting = {  
  5.         scrollable: true,  
  6.         scrollableHeight: '200px'  
  7.     } 
Fetch the data Menu Name from the database for showing in multiselect dropdown.
  1. $http.get('/home/getmenus').then(function (data) {  
  2.         angular.forEach(data.data, function (value, index) {  
  3.             $scope.Menus.push({ id: value.MenuID, label: value.MenuName });  
  4.         });  
  5.     }) 
I have accessed here to get the request of Home Controller action method. 
  1. $http.get('/home/getmenus'
Post or submit the selected items from multiselect dropdown to the Server.
  1. $scope.SubmittedMenus = [];  
  2.    $scope.SubmitData = function () {  
  3.        var menuIds = [];  
  4.        angular.forEach($scope.MenusSelected, function (value, index) {  
  5.            menuIds.push(value.id);  
  6.        });  
  7.   
  8.        var data = {  
  9.            menuIds: menuIds  
  10.        };  
  11.   
  12.        $http({  
  13.            method: "POST",  
  14.            url: "/home/savedata",  
  15.            data: JSON.stringify(data)  
  16.        }).then(function (data) {  
  17.            $scope.SubmittedMenus = data.data;  
  18.        }, function (error) {  
  19.            alert('Check Your Server Running Or Not!');  
  20.        })  
  21.    } 
 I access here the post request of Home Controller action method.
  1. $http({  
  2.            method: "POST",  
  3.            url: "/home/savedata"
  1. url: "/home/savedata" 
Note
 
A very important role that AngularJS will play is to show an alert message whether your Server is Running or Not when a user clicks the button.
  1. function (error) {  
  2.             alert('Check Your Server Running Or Not!');  
  3.         }) 
Step 5
 
Create a Controller
 
Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer.
Go to Add > Controller > Enter Controller name > select Templete "empty MVC Controller"> Add.

Here, I have created a Controller named "HomeController".
 
Code Ref
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace SatyaCheckboxAngularjs.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         public ActionResult Index()  
  12.         {  
  13.             return View();  
  14.         }  
  15.   
  16.         public JsonResult getmenus()  
  17.         {  
  18.             using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
  19.             {  
  20.                 return new JsonResult { Data = dc.Menus.ToList(), JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
  21.             }  
  22.         }  
  23.   
  24.         [HttpPost]  
  25.         public JsonResult savedata(int[] menuIds)  
  26.         {  
  27.             List<Menu> list = new List<Menu>();  
  28.             if (menuIds != null)  
  29.             {  
  30.                 using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
  31.                 {  
  32.                     list = dc.Menus.Where(a => menuIds.Contains(a.MenuID)).ToList();  
  33.                 }  
  34.             }  
  35.             return new JsonResult { Data = list };  
  36.         }  
  37.   
  38.         public ActionResult About()  
  39.         {  
  40.             ViewBag.Message = "Your application description page.";  
  41.   
  42.             return View();  
  43.         }  
  44.   
  45.         public ActionResult Contact()  
  46.         {  
  47.             ViewBag.Message = "Your contact page.";  
  48.   
  49.             return View();  
  50.         }  
  51.     }  

Code Decription
 
Add another action to your Controller for getting the data from a database for showing in the multiselect dropdown.
  1. public JsonResult getmenus()  
  2.        {  
  3.            using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
  4.            {  
  5.                return new JsonResult { Data = dc.Menus.ToList(), JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
  6.            }  
  7.        }  
Here, "CrystalGranite2016Entities"  is the entity data model. Here JsonResult represnts a Class That is used to send JSON-FORMATTED content to the response. JsonRequestBehavior specified whether HTTP GET requests from the client are allowed.
  1. JsonRequestBehavior.AllowGet=0 
Then, it gets or sets the value whether HTTP GET requests from the client are allowed and menu will display.
  1. return new JsonResult { Data = dc.Menus.ToList(), JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
Add one more action into your controller for post data if selected data from multiselect dropdown  to the server.
  1. [HttpPost]  
  2.         public JsonResult savedata(int[] menuIds)  
  3.         {  
  4.             List<Menu> list = new List<Menu>();  
  5.             if (menuIds != null)  
  6.             {  
  7.                 using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
  8.                 {  
  9.                     list = dc.Menus.Where(a => menuIds.Contains(a.MenuID)).ToList();  
  10.                 }  
  11.             }  
  12.             return new JsonResult { Data = list };  
  13.         } 
It is the Http post request.  just sending back the selected categories from here but  menuIds parameter has a big role here. using menuIds parameter u can add your other functianility here.
 
Here based on checkbox selection , the selected checkboxes records will show in below table after button click event.
  1. if (menuIds != null)  
  2.            {  
  3.                using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
  4.                {  
  5.                    list = dc.Menus.Where(a => menuIds.Contains(a.MenuID)).ToList();  
  6.                }  
  7.            }  
  8.            return new JsonResult { Data = list }; 
Step-6
 
View for your multiselect dropdown Checkbox list named "Index.cshtml".
 
Code Ref
  1. @{  
  2.     ViewBag.Title = "Satyaprakash Dynamic Checkbox";  
  3. }  
  4.   
  5. <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" />  
  6. <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular.js"></script>  
  7. <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>  
  8. <script src="~/Scripts/angularjs-dropdown-multiselect.js"></script>  
  9. <script src="~/Scripts/MyApp.js"></script>  
  10.   
  11. <style>  
  12.     .body-content {  
  13.         padding-top: 50px;  
  14.     }  
  15.   
  16.     .checkbox {  
  17.         padding: 0;  
  18.         margin: 0;  
  19.     }  
  20.   
  21.     .dropdown-menu {  
  22.         overflow: auto !important;  
  23.     }  
  24.   
  25.     .form-group div {  
  26.         display: inline-block;  
  27.         margin-right: 10px;  
  28.     }  
  29.   
  30.     table {    
  31.             font-family: arial, sans-serif;    
  32.             border-collapse: collapse;    
  33.             width: 100%;    
  34.         }    
  35.     
  36.         td, th {    
  37.             border: 1px solid #dddddd;    
  38.             text-align: left;    
  39.             padding: 8px;    
  40.         }    
  41.     
  42.         tr:nth-child(even) {    
  43.             background-color: #dddddd;    
  44.         }    
  45.     
  46.         .button {    
  47.             background-color: #4CAF50;    
  48.             border: none;    
  49.             color: white;    
  50.             padding: 15px 32px;    
  51.             text-align: center;    
  52.             text-decoration: none;    
  53.             display: inline-block;    
  54.             font-size: 16px;    
  55.             margin: 4px 2px;    
  56.             cursor: pointer;    
  57.         }    
  58.     
  59.         .button4 {    
  60.             border-radius: 9px;    
  61.         }    
  62.     
  63. </style>  
  64. <h2 style="background-color: blue;color: white; text-align: center; font-style: oblique">SATYAPRAKASH's DYNAMIC CHECKBOX USING ANGULARJS</h2>  
  65. <fieldset>  
  66.     <legend style="font-family:Arial Black;color:orangered">MODULES CHECKBOX USING ANGULARJS</legend>  
  67.     <div ng-app="MyApp" ng-controller="multiselectdropdown">  
  68.         <div class="container" style="margin:50px">  
  69.             <form class="form-inline" name="myForm" role="form" ng-submit="SubmitData()">  
  70.                 <div class="form-group">  
  71.                     <label style="color:Blue">Register Modules Here</label>  
  72.                     <div ng-dropdown-multiselect="" extra-settings="dropdownSetting"  
  73.                          options="Menus" selected-model="MenusSelected" checkboxes="true"></div>  
  74.                 </div>  
  75.                 <input type="submit" class="button button4" value="Show" />  
  76.             </form>  
  77.             <div style="margin-top:40px" ng-if="SubmittedMenus.length > 0">  
  78.                 <h2 style="color:Blue">Modules Selected For Website</h2>  
  79.                 <table align="center" border="1" cellpadding="4" cellspacing="4">  
  80.                     <thead>  
  81.                         <tr>  
  82.                             <th style="background-color: Yellow;color: blue">Module ID</th>  
  83.                             <th style="background-color: Yellow;color: blue">Module Name</th>  
  84.                         </tr>  
  85.                     </thead>  
  86.                     <tbody>  
  87.                         <tr ng-repeat="cat in SubmittedMenus">  
  88.                             <td>{{cat.MenuID}}</td>  
  89.                             <td>{{cat.MenuName}}</td>  
  90.                         </tr>  
  91.                     </tbody>  
  92.                 </table>  
  93.             </div>  
  94.   
  95.             <div style="margin-top:40px" ng-if="SubmittedMenus.length < 1">  
  96.                 <label style="color:red">No Modules Selected !</label>  
  97.             </div>  
  98.   
  99.         </div>  
  100.     </div>  
  101.     </fieldset>  
  102. <footer>  
  103.     <p style="background-color: blue; font-weight: bold; color:white; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  104. </footer>    
Code Description
 
Load bootstrap css.
  1. <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" /> 
load angularjs library & lodash js.
  1. <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular.js"></script> 
  1. <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular.js"></script>  
  2. <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script> 
load our js of MyApp.js file and angularjs-dropdown-multiselect directive .
  1. <script src="~/Scripts/angularjs-dropdown-multiselect.js"></script>  
  2. <script src="~/Scripts/MyApp.js"></script> 
added some  css here.
  1. <style>  
  2.     .body-content {  
  3.         padding-top50px;  
  4.     }  
  5.   
  6.     .checkbox {  
  7.         padding0;  
  8.         margin0;  
  9.     }  
  10.   
  11.     .dropdown-menu {  
  12.         overflowauto !important;  
  13.     }  
  14.   
  15.     .form-group div {  
  16.         display: inline-block;  
  17.         margin-right10px;  
  18.     }  
  19.   
  20.     table {    
  21.             font-familyarialsans-serif;    
  22.             border-collapsecollapse;    
  23.             width100%;    
  24.         }    
  25.     
  26.         td, th {    
  27.             border1px solid #dddddd;    
  28.             text-alignleft;    
  29.             padding8px;    
  30.         }    
  31.     
  32.         tr:nth-child(even) {    
  33.             background-color#dddddd;    
  34.         }    
  35.     
  36.         .button {    
  37.             background-color#4CAF50;    
  38.             bordernone;    
  39.             colorwhite;    
  40.             padding15px 32px;    
  41.             text-aligncenter;    
  42.             text-decorationnone;    
  43.             display: inline-block;    
  44.             font-size16px;    
  45.             margin4px 2px;    
  46.             cursorpointer;    
  47.         }    
  48.     
  49.         .button4 {    
  50.             border-radius: 9px;    
  51.         }    
  52.     
  53. </style> 
Used Directives and multiselet dropdown with dynamic checkboxes will let user select and click button.
  1. <div ng-app="MyApp" ng-controller="multiselectdropdown">  
  2.         <div class="container" style="margin:50px">  
  3.             <form class="form-inline" name="myForm" role="form" ng-submit="SubmitData()">  
  4.                 <div class="form-group">  
  5.                     <label style="color:Blue">Register Modules Here</label>  
  6.                     <div ng-dropdown-multiselect="" extra-settings="dropdownSetting"  
  7.                          options="Menus" selected-model="MenusSelected" checkboxes="true"></div>  
  8.                 </div>  
  9.                 <input type="submit" class="button button4" value="Show" />  
  10.             </form> 
  1. <div ng-app="MyApp" ng-controller="multiselectdropdown">  
  2.         <div class="container" style="margin:50px"
Show posted Menus from server and put in table.
  1. <div style="margin-top:40px" ng-if="SubmittedMenus.length > 0">  
  2.                <h2 style="color:Blue">Modules Selected For Website</h2>  
  3.                <table align="center" border="1" cellpadding="4" cellspacing="4">  
  4.                    <thead>  
  5.                        <tr>  
  6.                            <th style="background-color: Yellow;color: blue">Module ID</th>  
  7.                            <th style="background-color: Yellow;color: blue">Module Name</th>  
  8.                        </tr>  
  9.                    </thead>  
  10.                    <tbody>  
  11.                        <tr ng-repeat="cat in SubmittedMenus">  
  12.                            <td>{{cat.MenuID}}</td>  
  13.                            <td>{{cat.MenuName}}</td>  
  14.                        </tr>  
  15.                    </tbody>  
  16.                </table>  
  17.            </div> 
If no posted menu from server then it will show a message to the user.
  1. <div style="margin-top:40px" ng-if="SubmittedMenus.length < 1">  
  2.                <label style="color:red">No Modules Selected !</label>  
  3.            </div> 
Here ng-if directive has a great role about condition.
  1. ng-if="SubmittedMenus.length 
Using abel control it will show a warning message with red color.
  1. <label style="color:red">No Modules Selected !</label> 
Added footer to check current date time.
  1. <footer>  
  2.     <p style="background-color: blue; font-weight: bold; color:white; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  3. </footer>   
OUTPUT
 
The URL is,
 
http://localhost:2127/Home/Index .
 
Check for Dynamic Checkboxes In Multi select Dropdownlist control. Here u can check no checkbox selected so, the warning message is showing in red mark.
 

Show selected checkboxes records in the table.
 
If Server Not Found....
 
 
 
Multiplatform Support Using Bootstrap.
 
 
 
Gif Images,
 
 
 
AngularJS will show alert message If your Server Running or not Also u can say Internet connection available or not when user clicks the button.
 
 
 
Module Summary
  • Checkbox using dynamic concept.
  • Checkbox data will save in html table in mvc.
  • Check server not found or internet issue using AnguarJS Component.
  • Booystrap support.