I am creating an web page in which have a Dropdownlist
. I have to retrieve data for the drop_down_list from the database. Is there any way to get data from the data
It is just a simple two step process:
Step1 :Action method code
public ActionResult Index()
{
ViewBag.users = db.users.ToList();
}
Step2: cshtml code
@Html.DropDownListFor(model => model.someId, new SelectList(ViewBag.users, "userId", "userName"), "Select users")
Note: with this, you can bind n number of data from the database to dropdownlist
Hope it was useful
Thanks
Karthik
You need to create Select List of Items :
Your Action with List of Items in View Bag :
public ActionResult ActionName()
{
List<SelectListItem> Items = new List<SelectListItem>();
CustReportName.Add(new SelectListItem() { Text = "List1", Value = "1", Selected = false });
CustReportName.Add(new SelectListItem() { Text = "List2", Value = "2", Selected = true });
ViewBag.ListItems = Items;
return View("ViewName");
}
For Multiple values from database table:
public ActionResult ActionName()
{
IEnumerable<SelectListItem> ItemsList = from item in YourTableObject
select new SelectListItem
{
Value = Convert.ToString(item.Id),
Text = item.ItemName
};
ViewBag.ListItems = new SelectList(ItemsList, "Value", "Text");
return View("ViewName");
}
Your DropdownList On view :
@Html.DropDownListFor(model => model.ItemId, new SelectList(ViewBag.ItemList, "Value", "Text", 0), "-Select Item-", new { @class = "form-control", @id = "ItemId" })
Cheers !!