How to get data to Dropdownlist from database in html view

前端 未结 2 972
滥情空心
滥情空心 2021-01-29 15:14

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

2条回答
  •  情歌与酒
    2021-01-29 15:23

    You need to create Select List of Items :

    Your Action with List of Items in View Bag :

    public ActionResult ActionName()
    {
     List Items = new List();
            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 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 !!

提交回复
热议问题