MultiSelect DropdownList Using jQuery in Asp.Net MVC and C#.Net :
first we will create a new mvc application and add the a model class file in model folder. In this model class file add the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
public class CountryModel
{
public List<Country> CountryList { get; set; }
public string SelectedCountryId { get; set; }
}
public class Country
{
public string CountryName { get; set; }
}
}
Now add a controller class file and add the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.CountryList = new List<Country>();
objcountrymodel.CountryList = CountryDate();
return View(objcountrymodel);
}
public List<Country> CountryDate()
{
List<Country> objcountry = new List<Country>();
objcountry.Add(new Country { CountryName = "America" });
objcountry.Add(new Country { CountryName = "India" });
objcountry.Add(new Country { CountryName = "Sri Lanka" });
objcountry.Add(new Country { CountryName = "China" });
objcountry.Add(new Country { CountryName = "Pakistan" });
return objcountry;
}
}
}
In above code I have created a collection of country. This list we will bind with the dropdown list. Now create the view and add the below code into the view.
@model MvcApplication1.Models.CountryModel
@{
ViewBag.Title = "MultiSelect DropdownList Using jQuery in Asp.Net MVC and C#.Net";
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="../../Scripts/jquery.sumoselect.js" type="text/javascript"></script>
<link href="../../Css/dropdownliststyle.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
window.asd = $('.ddlMultiSlectBox).SumoSelect({ csvDispCount: 4 });
});
</script>
Country:
@Html.DropDownListFor(m => m.SelectedCountryId, new SelectList(Model.CountryList, "CountryName", "CountryName"), new {@multiple="multiple",@placeholder="Please select country", @class="ddlMultiSlectBox" })
Here in this code I have added the css and jQuery library reference and used sumoselect function to show multi select dropdown list.
Now we have done run the application to check the output.
