Amit Sharma
Amit Sharma

Reputation: 1088

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.

Upvotes: 0

Views: 2375

Answers (1)

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

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)

Upvotes: 1

Related Questions