Friday, August 9, 2019

Multiselect dropdown with checkbox in angularjs

Just follow the following steps in order implement multiselect dropdown with checkbox in AngularJS

Here In this article, I have used Visual Studio 2013 

Step-1: Create New Project.

Go to File > New > Project > ASP.NET  Web Application (under web) > Entry Application Name > Click OK > Select Empty template > Checked MVC (under "Add folders and core references for" option) > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table.

In this example, I have used 1 table as below


Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >


Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Create a javascript file for angular components.

Here I have created a folder named "Scripts" first, and then I have added a javascript file for add angular components (module, controller etc). Here we will fetch menu data from the database.
Right Click on your solution file (from solution explorer) > Add > New Folder > Renamed your folder. and then
Right click on your folder (just created) > Add > New Item > select "javascript" file > Enter name (here "MyApp.js")> Ok.
Write following code 
  1. var app = angular.module('MyApp', ['angularjs-dropdown-multiselect']);
  2. app.controller('multiselectdropdown', ['$scope', '$http', function ($scope, $http) {
  3. //define object
  4. $scope.CategoriesSelected = [];
  5. $scope.Categories = [];
  6. $scope.dropdownSetting = {
  7. scrollable: true,
  8. scrollableHeight : '200px'
  9. }
  10. //fetch data from database for show in multiselect dropdown
  11. $http.get('/home/getcategories').then(function (data) {
  12. angular.forEach(data.data, function (value, index) {
  13. $scope.Categories.push({ id: value.CategoryID, label: value.CategoryName });
  14. });
  15. })
  16. //post or submit selected items from multiselect dropdown to server
  17. $scope.SubmittedCategories = [];
  18. $scope.SubmitData = function () {
  19. var categoryIds = [];
  20. angular.forEach($scope.CategoriesSelected, function (value, index) {
  21. categoryIds.push(value.id);
  22. });
  23.  
  24. var data = {
  25. categoryIds: categoryIds
  26. };
  27.  
  28. $http({
  29. method: "POST",
  30. url: "/home/savedata",
  31. data:JSON.stringify(data)
  32. }).then(function (data) {
  33. $scope.SubmittedCategories = data.data;
  34. }, function (error) {
  35. alert('Error');
  36. })
  37. }
  38. }])
you can see here I have included the angularjs-dropdown-multiselect module in our module (here "MyApp") for use ng-dropdown-multiselect directive for getting multiselect dropdown with checkboxes.

Step-6: Create a Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller named "HomeController"


Step-7: Add new action into your controller for getting the view, where we will show a multiselect dropdown with checkboxes.

Here I have added "Index" Action into "Home" Controller. Please write this following code
  1. public ActionResult Index()
  2. {
  3. return View();
  4. }

Step-8: Add an another action into your controller for getting data from a database for showing in multiselect dropdown.

  1. public JsonResult getcategories()
  2. {
  3. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  4. {
  5. return new JsonResult { Data = dc.Categories.ToList(), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  6. }
  7. }

Step-9: Add one more action into your controller for post data (selected data from multiselect dropdown) to the server.

  1. [HttpPost]
  2. public JsonResult savedata(int[] categoryIds)
  3. {
  4. //for make the application simple I am just sending back the selected categories from here
  5. // but you can do additional work here with categoryIds parameter
  6. List<Category> list = new List<Category>();
  7. if (categoryIds != null)
  8. {
  9. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  10. {
  11. list = dc.Categories.Where(a => categoryIds.Contains(a.CategoryID)).ToList();
  12. }
  13.  
  14. // do your additional work here
  15. }
  16. return new JsonResult { Data = list };
  17. }

Step-10: Add view for your Action & design for showing multiselect dropdown list.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
HTML Code 
  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <h2>Multiselect dropdown with checkbox in angularjs</h2>
  5. @* Load bootstrap css *@
  6. <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" />
  7. @* load angularjs library & lodash js *@
  8. <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular.js"></script>
  9. <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
  10. @* load our js ("MyApp" here) file and angularjs-dropdown-multiselect directive *@
  11. <script src="~/Scripts/angularjs-dropdown-multiselect.js"></script>
  12. <script src="~/Scripts/MyApp.js"></script>
  13. @* HTML Code *@
  14.  
  15. @* I have added some css here for looks good *@
  16. <style>
  17. .body-content{padding-top:50px}
  18. .checkbox{padding:0;margin:0;}
  19. .dropdown-menu{overflow:auto !important;}
  20. .form-group div{display:inline-block; margin-right:10px}
  21. </style>
  22.  
  23. <div ng-app="MyApp" ng-controller="multiselectdropdown">
  24. <div class="container" style="margin:50px">
  25. <form class="form-inline" name="myForm" role="form" ng-submit="SubmitData()">
  26. <div class="form-group">
  27. <label>Subscribe for categories : </label>
  28. @* Directive *@
  29. <div ng-dropdown-multiselect="" extra-settings="dropdownSetting"
  30. options="Categories" selected-model="CategoriesSelected" checkboxes="true"></div>
  31. </div>
  32. <button type="submit" class="btn btn-primary">Submit</button>
  33. </form>
  34.  
  35. @* Show posted categories (from server) *@
  36. <div style="margin-top:40px" ng-if="SubmittedCategories.length > 0">
  37. <h2>Selected Categories</h2>
  38. <table class="table table-responsive table-bordered">
  39. <thead>
  40. <tr>
  41. <th>ID</th>
  42. <th>Category Name</th>
  43. </tr>
  44. </thead>
  45. <tbody>
  46. <tr ng-repeat="cat in SubmittedCategories">
  47. <td>{{cat.CategoryID}}</td>
  48. <td>{{cat.CategoryName}}</td>
  49. </tr>
  50. </tbody>
  51. </table>
  52. </div>
  53. </div>
  54. </div>
Step-11: Run application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...