ASP.NET MVC – 填充下拉列表
我是ASP.NET MVC的新手。 我正在试图弄清楚如何从我的数据库中的值创建一个基本的下拉列表。 在ASP.NET Web表单中,我知道我可以加载下拉列表,如下所示:
Page.aspx
Page.aspx.cs
void myDropDownList_Load(object sender, EventArgs e) { if (Page.IsPostBack == false) { List people = GetPeopleFromDatabase(); myDropDownList.DataSource = people; myDropDownList.DataBind(); } }
我如何在ASP.NET MVC中执行相同类型的操作? 谢谢!
模型
public class EditSongViewModel { public int AlbumId { get; set; } public string Title { get; set; } public int TrackNumber { get; set; } public IEnumerable Albums { get; set; } }
扩展方法
public static IEnumerable ToSelectListItems( this IEnumerable albums, int selectedId) { return albums.OrderBy(album => album.Name) .Select(album => new SelectListItem { Selected = (album.ID == selectedId), Text = album.Name, Value = album.ID.ToString() }); }
从数据库获取数据
model.Albums = _repository.FindAllAlbums().ToSelectItems(selectedId);
视图
@Html.DropDownList("AlbumId", Model.Albums)
或者更好的是:
@Html.DropDownListFor(model => model.AlbumId, Model.Albums)
看看这篇解释它的博客文章:
下拉列表和ASP.NET MVC
在MVC2中,在视图和控制器中使用<%=Html.DropListFor(x => x.MemberName, Model.DropListItems)%>
,使用包含数据库中项目的新SelectList
填充DropListItems。
我相信书呆子晚餐样本包括这个,如果你是MVC的新手,你应该真正地通过创建书呆子晚餐应用程序,因为你从中学到了很多东西,即使你打算不使用他们使用的东西。