Saturday, 21 October 2017

MVC MultiSelect (Multiple Selection) DropdownList with CheckBoxes Using jQuery

In this tutorial, I am going to explain you how to implement multiple selection (MultiSelect) DropDownList with CheckBox in MVC using jQuery, Bootstrap and MultiSelect JS.

Creating MVC Model

First of all, we need to create model. Write click on Models folder and add a new class name as CountryModel. Replace all code with below code. CountryList property is used to store List of Country and SelCountry property is used to store selected country while passing to the controller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Models
{
    public class CountryModel
    {
        public CountryModel()
        {
            CountryList = new List<SelectListItem>();
        }
        public List<SelectListItem> CountryList { get; set; }

        public string SelCountry { get; set; }
    }
}

Creating MVC Controller

Now right click on Controller folder and add new empty controller name as Home. Replace all code with below code. Here Index action method is used to return SelectListItem of Country and SavaCountry method is called on click of Submit of Button from view. In SaveCountry method, SelCountry parameter stores all the selected item's Id in array.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
public class HomeController : Controller
{

    [HttpGet]
    public ActionResult Index()
    {
        return View(GetCountryList());
    }

    [NonAction]
    public CountryModel GetCountryList()
    {
        CountryModel obj = new CountryModel();
        obj.CountryList.Add(new SelectListItem { Text = "India", Value = "1" });
        obj.CountryList.Add(new SelectListItem { Text = "USA", Value = "2" });
        obj.CountryList.Add(new SelectListItem { Text = "UK", Value = "3" });
        obj.CountryList.Add(new SelectListItem { Text = "Australia", Value = "4" });
        return obj;
    }

    [HttpPost]
    public ActionResult SavaCountry(string[] SelCountry)
    {
        if (SelCountry != null)
        {
            string Country = string.Join(",", SelCountry);

            //
            // write your code to save into database
            //
        }
        return View("Index", GetCountryList());
    }
}
}

Creating MVC View

Now, right click on Index action method and add new empty view without any layout view and Give its name 'Index'. Now go to Views/Home folder and Open Index.cshtml file. Replace all code with below code. Here in script JS files, First is jQuery file and Second, Third is bootstrap JS and CSS files and Fourth and Fifth file is MultiSelect JS and CSS Files. Make sure all files is loaded when application runs.
Here includeSelectAllOption is set to true to include Select All text at first position in Select List.

@model WebApplication1.Models.CountryModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js" type="text/javascript"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>

<script type="text/javascript">
    var j = jQuery.noConflict();
    j(function () {
        j('#SelCountry').multiselect({
            includeSelectAllOption: true
        });
    });
</script>
</head>
<body>
@using (Html.BeginForm("SavaCountry", "Home", FormMethod.Post))
{
    <div style="width:500px;height:auto; border:1px solid red; margin-top:50px;margin-left:150px; padding:5px;">
        <table>
            <tr>
                <td><b>Country List</b></td>
                <td>
                    @Html.DropDownListFor(m => m.SelCountry, new SelectList(Model.CountryList, "Value", "Text"), new { @multiple = "multiple" })
                    @*@Html.DropDownListFor(m => m.SelCountry, Model.CountryList, new { @multiple = "multiple" })*@
                </td>
                <td>
                    <button class="btn btn-success btn-md" type="submit">Submit To Database</button>
                </td>
            </tr>
        </table>
    </div>
}
</body>
</html>

Now, build and run your application and output can be seen as below.

MVC MultiSelect (Multiple Selection) DropdownList with CheckBoxes Using jQuery

Now, click on Submit To Database button and selected value can be seen as below.

Passing dropdownlist data from view to controller

Now, to remove Select all option from list, remove includeSelectAllOption from jQuery code or set it to false. You can see Select all option is removed from list.

Remove Select all from Multiselect JS

Select All by-default

Here, when view is loaded, no item is selected. To make all items selected by default, add below lines of code in JS code.

<script type="text/javascript">
    var j = jQuery.noConflict();
    j(function () {
        j('#SelCountry').multiselect({
            includeSelectAllOption: false
        });
        j("#SelCountry").multiselect('selectAll', false);
        j("#SelCountry").multiselect('updateButtonText');
    });
</script>

Here all item is selected by default when view is loaded.

Select all by default in multiselect js
Share:

2 comments:

  1. Thank you this is very helpful. Also what can we do incase for edit operation, where we need to display some country initially selected?

    ReplyDelete
    Replies
    1. Hi Sagar,
      Thanks for visiting ASPArticles. I had tried to create a demo based on your requirement. I tried to build logic for auto-selected dropdown.

      Click here to read

      Delete

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON