问题
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.
回答1:
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)
来源:https://stackoverflow.com/questions/27797482/how-to-bind-html-drop-down-list-in-mvc-razor-view