How to bind HTML Drop Down List in MVC Razor view

邮差的信 提交于 2019-12-25 09:08:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!