How to get data to Dropdownlist from database in html view

雨燕双飞 提交于 2019-12-04 07:11:09

问题


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 database to the html view my html code:

<select name="drop down"><option value="1">@test.list[i]</option></select>

I got the database value to the list variable but I don't know how to pass the data to the html view. Please help me in this issue.Thanks


回答1:


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 !!




回答2:


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



来源:https://stackoverflow.com/questions/44429163/how-to-get-data-to-dropdownlist-from-database-in-html-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!