Search code examples
asp.net-mvcasp.net-mvc-4razor-2

How to bind HTML Drop Down List in MVC Razor view


in my project i'm getting IEnumerable collection, now want to bind this my Html Drop Down list my razor view code is as:

 @if (Model.LanguageNavigationLinkItem != null)
     {
       // drop down list item Collection
       var ddlItem = Model.LanguageNavigationLinkItem;
       @Html.DropDownList(ddlItem.ToList(),"-- Select Item --")       
     } 

i couldn't bind this collection with my drop down list please any one help me.


Solution

  • Here is an example to bind dropdown using ViewBag. You can also use model to bind dropdown in similar way.

    Controller Code

    //Getting list of employees from DB.
    var list = ent.Employees.SqlQuery(ent.Queries.FirstOrDefault().Query1).ToList<Employee>();
    List<SelectListItem> selectlist = new List<SelectListItem>();
    foreach (Employee emp in list)
    {
       selectlist.Add(new SelectListItem { Text = emp.Name, Value = emp.Id.ToString() });
    }
    ViewBag.SelectList = selectlist;
    

    View

    @Html.DropDownList("name",(IEnumerable<SelectListItem>)ViewBag.SelectList)