-->

Multiselect dropdown with checkbox in angularjs



Introduction

In one of my previous article, we have seen  how to implement cascading dropdownwith AngularJS and ASP.NET MVC. Today I am going to explain about multiselect dropdown with checkboxes in AngularJS and asp.net MVC (server-side) application.

In one of my recent project, there was a client requirement to provide an option to users for select multiple newsletters for subscription in registration page in angularjs application. In that page, we can use multiple checkboxes, but the problem was, it takes quite a lot of space which does not always fit in the UI requirements.
To overcome this, we created a multiselect dropdown with checkboxes to use a dropdown like a feature that can select multiple values.
Here in this example, I have used an angular directive angularjs-dropdown-multiselect, this directive gives us a Bootstrap Dropdown with the power of AngularJS directives. It's very easy to implement and has lots of features.

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
var app = angular.module('MyApp', ['angularjs-dropdown-multiselect']);
app.controller('multiselectdropdown', ['$scope', '$http', function ($scope, $http) {
    //define object 
    $scope.CategoriesSelected = [];
    $scope.Categories = [];
    $scope.dropdownSetting = {
        scrollable: true,
        scrollableHeight : '200px'
    }
    //fetch data from database for show in multiselect dropdown
    $http.get('/home/getcategories').then(function (data) {
        angular.forEach(data.data, function (value, index) {
            $scope.Categories.push({ id: value.CategoryID, label: value.CategoryName });
        });
    })
    //post or submit selected items from multiselect dropdown to server
    $scope.SubmittedCategories = [];
    $scope.SubmitData = function () {
        var categoryIds = [];
        angular.forEach($scope.CategoriesSelected, function (value, index) {
            categoryIds.push(value.id);
        });

        var data = {
            categoryIds: categoryIds
        };

        $http({
            method: "POST",
            url: "/home/savedata",
            data:JSON.stringify(data)
        }).then(function (data) {
            $scope.SubmittedCategories = data.data;
        }, function (error) {
            alert('Error');
        })
    }
}])
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
public ActionResult Index()
{
    return View();
}

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

public JsonResult getcategories()
{
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        return new JsonResult { Data = dc.Categories.ToList(),  JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}

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

[HttpPost]
public JsonResult savedata(int[] categoryIds)
{
    //for make the application simple I am just sending back the selected categories from here
    // but you can do additional work here with categoryIds parameter
    List<Category> list = new List<Category>();
    if (categoryIds != null)
    {
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            list = dc.Categories.Where(a => categoryIds.Contains(a.CategoryID)).ToList();
        }

        // do your additional work here
    }
    return new JsonResult { Data = list };
}

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
@{
    ViewBag.Title = "Index";
}
<h2>Multiselect dropdown with checkbox in angularjs</h2>
      @* Load bootstrap css *@
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" />
      @* load angularjs library & lodash js *@
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
        @* load our js ("MyApp" here) file and angularjs-dropdown-multiselect directive *@
<script src="~/Scripts/angularjs-dropdown-multiselect.js"></script>
<script src="~/Scripts/MyApp.js"></script>
        @* HTML Code *@

@* I have added some css here for looks good *@
<style>
    .body-content{padding-top:50px}
    .checkbox{padding:0;margin:0;}
    .dropdown-menu{overflow:auto !important;}
    .form-group div{display:inline-block; margin-right:10px}
</style>

<div ng-app="MyApp" ng-controller="multiselectdropdown">
    <div class="container" style="margin:50px">
        <form class="form-inline" name="myForm" role="form" ng-submit="SubmitData()">
            <div class="form-group">
                <label>Subscribe for categories : </label>
                @* Directive *@
                <div ng-dropdown-multiselect="" extra-settings="dropdownSetting" 
                     options="Categories" selected-model="CategoriesSelected" checkboxes="true"></div>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>

        @* Show posted categories (from server) *@
        <div style="margin-top:40px" ng-if="SubmittedCategories.length > 0">
            <h2>Selected Categories</h2>
            <table class="table table-responsive table-bordered">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Category Name</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="cat in SubmittedCategories">
                        <td>{{cat.CategoryID}}</td>
                        <td>{{cat.CategoryName}}</td>
                    </tr>
                </tbody>
            </table>  
        </div>
    </div>
</div>

Step-11: Run application.



Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.