Reputation: 15
View:
<select multiple="" id="e2" tabindex="-1" class="select2-hidden-accessible" name="e2" aria-hidden="true">
<option value="PDS.RICE">PDS.RICE</option>
<option value="PDS.WHEAT">PDS.WHEAT</option>
<option value="PDS.DAL CHANNA">PDS.DAL CHANNA</option>
<option value="PDS.DAL KALA CHANNA">PDS.DAL KALA CHANNA</option>
</select>
Controller:
public ActionResult Getitems()
{
var items = (from m in db.ItemMasters select m).ToList();
ViewBag.items = items;
return View();
}
Model:
public class ItemMaster
{
[Key]
public int ItemId { get; set; }
public string Item_Name { get; set; }
}
I am trying to fetch the data from database in the controller, but unable to bind the ViewBag
data to the select2-hidden-accessible
in view.
Upvotes: 0
Views: 4253
Reputation: 656
You can bind dropdownlist by using ViewBag, below is the code :
Controller :
public ActionResult Getitems()
{
var itemList = new List<SelectListItem>
{
new SelectListItem
{
Text = "RICE",
Value = "RICE"
},
new SelectListItem
{
Text = "WHEAT",
Value = "WHEAT"
}
};
ViewBag.ItemList = new SelectList(itemList, "Value", "Text");
return View();
}
View :
Add below scripts in your head tag.
<head>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/select2.js"></script>
<link href="~/Content/select2.css" rel="stylesheet" />
</head>
@Html.DropDownList("e2", (SelectList) ViewBag.ItemList, new {@class = "js-example-basic-multiple",multiple="multiple" })
Initialize the select2 plugin.
<script>
$(".js-example-basic-multiple").select2();
</script>
Upvotes: 1