Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Hi I am new to MVC and want to know how to bind dropdownlist from list and from database.

I need simple examples. A very simple Examples.
Thanks
Posted

drop.cshtml Code

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var listItems = new List<SelectListItem>();
    listItems.Add(new SelectListItem { Text = String.Empty, Value = String.Empty });
    foreach (var name in ViewBag.Names)
    {
        listItems.Add(new SelectListItem { Text = name, Value = name });
    }
}
<h2>
    Index</h2>
@Html.DropDownList("dropDownList", listItems)


Controller:

SQL
public ActionResult drop()
      {
          List<string> abc=new List<string>(2);
          var q = from a in objContext.Details
                  select a;
          foreach (var i in q)
          {
              abc.Add(i.Name);
          }
          ViewBag.Names = abc;
          return View(q);
      }
 
Share this answer
 
Comments
member60 25-May-12 2:22am    
my 5!
Kaushal Parekh 22-Mar-13 9:21am    
That very nice explanation. But somewhat problem is still unsolved.
I need full code in VB.
At the line : listItems.Add(new SelectListItem { Text = String.Empty, Value = String.Empty });

I couldn't be able to convert it into VB.
 
Share this answer
 
Comments
Mukesh.Ce62 23-Feb-13 2:44am    
How to bind textfiled and valuefield data in dropdowbliast from database?
Avik Ghosh22 5-Mar-13 0:30am    
thank u bro...good link...5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900