Sunday, 31 December 2017

Convert ASP.NET MVC dropdownlist into multi select textbox using Chosen JS plugin

In this article, I am going to explain you how to convert asp.net mvc dropdownlist into multi select textbox using Chosen JS plugin. You can see in below figure how the dropdown will look like after converting into multi select textbox.

Convert ASP.NET MVC dropdownlist into multi select textbox using Chosen JS plugin

Creating ASP.NET MVC Empty Application

Now the next step is to create ASP.NET MVC empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 empty folder structure

Adding Models

Go to Models folder and add new class file CountryData.cs. Now replace all code with below code. Here we have one list property CountryList which is type of SelectListItem for holding list of country data. Four string property for holding Id of 4 different dropdowns which we will see in article.

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

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

        public List<SelectListItem> CountryList { get; set; }

        public string SelectedC1 { get; set; }
        public string SelectedC2 { get; set; }
        public string SelectedC3 { get; set; }
        public string SelectedC4 { get; set; }
    }
}

Adding Controller

Next step is to add controller to application. Go to controller folder and add new empty controller named as Home controller. Replace all code with below code. Here we have 2 Action methods, first method is get method, it is used to return Country List data to view and second method is post method which has 4 input parameters of type string array. These parameter will store the selected country's ID of all 4 dropdowns from view to controller.

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()
        {
            CountryData CD = new CountryData();

            CD.CountryList.Add(new SelectListItem { Text = "India", Value = "1" });
            CD.CountryList.Add(new SelectListItem { Text = "USA", Value = "2" });
            CD.CountryList.Add(new SelectListItem { Text = "UK", Value = "3" });
            CD.CountryList.Add(new SelectListItem { Text = "Australia", Value = "4" });

            // return country model to view with some data
            return View(CD);
        }

        [HttpPost]
        public ActionResult Index(string[] SelectedC1, string[] SelectedC2, string[] SelectedC3, string[] SelectedC4)
        {
            // do your database operation

            return View();
        }
    }
}

Installing Chosen using Nuget

Next step is to install Chosen JS. Right click on References and go to Manage NuGet Packages as shown below.

Manage NuGet Packages in ASP.NET MVC

After that a new window will open as shown below. Search for Harvest.Chosen and install it.

Installing Harvest.Chosen in ASP.Net MVC

After successful installation, you can see css file related to chosen is installed inside Content folder and chosen.jquery file is installed inside Scripts folder.

Adding View

Now, right click on home controller index action method, add new view and name Index. Select Empty template and uncheck Use layout page and click on Add as shown below.

Addling index view

Now go to Views / Home folder, open Index.cshtml file and replace all code with below code. Here first 3 files are jquery, chosen css and chosen.jquery files which is compulsory.
There are 4 dropdownlist, first is normal drowdown, second is dropdown with bootstrap applied, third is normal dropdown with chosen without multi select and fourth drowdown is with multi select enable using Chosen.
To enable multi select, use id or class selector to attach chosen plugin as shown below and set multiple="true" property of dropdown(in 4th dropdown).

Index.cshtml Code:
@model WebApplication1.Models.CountryData
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Convert ASP.NET MVC dropdownlist into multi select textbox using Chosen JS plugin</title>

    @*jquery file is required*@
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>

    @*chosen js and css file is required*@
    <link href="~/Content/chosen.css" rel="stylesheet" />
    <script src="~/Scripts/chosen.jquery.js"></script>

    @*bootstrap is optional*@
    <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>

    <script>
        $(function () {
            $("#SelectedC3").chosen(); // use id or class selector to attach chosen functionality
            $("#SelectedC4").chosen({ width: "95%" }); // set width of dropdown
        });
    </script>
</head>
<body>
    @using (Html.BeginForm(FormMethod.Post))
    {
        <div class="form-group" style="width:500px;margin-left:150px;">
            <table class="table">
                <tbody>
                    <tr>
                        <td>Normal dropdown</td>
                        <td style="width:300px !important;">
                            @Html.DropDownListFor(m => m.SelectedC1, new SelectList(Model.CountryList, "Value", "Text"))
                        </td>
                    </tr>
                    <tr>
                        <td>Normal dropdown with bootstrap applied</td>
                        <td>@Html.DropDownListFor(m => m.SelectedC2, new SelectList(Model.CountryList, "Value", "Text"), new { @class = "form-control" })</td>
                    </tr>
                    <tr>
                    <tr>
                        <td>Chosen dropdown with single selection</td>
                        <td>@Html.DropDownListFor(m => m.SelectedC3, new SelectList(Model.CountryList, "Value", "Text"))</td>
                    </tr>
                    <tr>
                        <td>Chosen Dropdown with multi selection</td>
                        <td>@Html.DropDownListFor(m => m.SelectedC4, new SelectList(Model.CountryList, "Value", "Text"), new { @multiple = "true" })</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <button class="btn btn-success btn-md" type="submit">Submit</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    }
</body>
</html>

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

Multi select using chosen jquery

Try to select for 4th dropdown as shown below. You can select many values from list as shown below.

Convert ASP.NET MVC dropdownlist into multi select textbox using Chosen JS plugin

Now you can search from dropdown and set default text if search item is not found and we can also set maximum number of item to be selected as shown below.

<script>
    $(function () {
        $("#SelectedC4").chosen({ width: "95%", max_selected_options: 2, no_results_text: "Oops, nothing found!" });
    });
</script>
Setting max limit and default text using chosen js

Now click on Submit button after selecting some items from 4th dropdown. You can find values of 4th dropdown in string array as shon below.

Submitting multi selected dropdown value from view to controller
Share:

0 comments:

Post a Comment

Email Subscription

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

Blog Archive

Ads By Chitika