Hi amars,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return View();
}
public JsonResult BindCategory()
{
List<Category> category = new NorthwindEntities().Categories.ToList();
List<SelectListItem> cat = new List<SelectListItem>();
foreach (var i in category)
{
cat.Add(new SelectListItem
{
Value = Convert.ToString(i.CategoryID),
Text = Convert.ToString(i.CategoryName)
});
}
return Json(cat, JsonRequestBehavior.AllowGet);
}
}
View
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script type="text/javascript">
$(function () {
var ddlCategory = $("#ddlCategory");
ddlCategory.empty().append('<option selected="selected" class="form-control select2" value="0" disabled = "disabled">Loading.....</option>');
$.ajax({
type: "POST",
url: "/Home/BindCategory",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
ddlCategory.empty()//.append('<option selected="selected" value="0">Select Category</option>');
$.each(response, function () {
ddlCategory.append($("<option></option>").val(this['Value']).html(this['Text'])).trigger("chosen:updated");
});
$(ddlCategory).select2({
placeholder: "Select",
allowClear: true
});
},
failure: function (response) { },
error: function (response) { }
});
});
</script>
<select id="ddlCategory" style="width: 300px;" multiple="multiple">
</select>
Screenshot
