MVC中使用DropDownListFor
1 查找DropDownListFor要绑定的数据源
IEnumerable<NewsType> newsTypeList = (from m in db.NewsType select m).ToList();//从数据库中查找数据。
SelectList slist = new SelectList(newsTypeList, "TypeId", "TypeName");//将查找出来的数据,转化为列表对象
ViewData["List"] = slist;//使用ViewData对象保存列表对象,在页面控件绑定时用到ViewData["List"]
2 在页面上进行绑定
<%: Html.DropDownListFor(model => model.TypeId,ViewData["List"] as SelectList, new { @id = "ddlType" })%>
3 显示指定项:语法其实和绑定是一样,程序自己会根据 model.TypeId的值,进行选择显示
<%: Html.DropDownListFor(model => model.TypeId,ViewData["List"] as SelectList, new { @id = "ddlType" })%>