How to get data to Dropdownlist from database in html view

前端 未结 2 971
滥情空心
滥情空心 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:21

    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

    0 讨论(0)
  • 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<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 !!

    0 讨论(0)
提交回复
热议问题