更新时间:2023-01-07 08:46:20
型号
public class EditSongViewModel
{
public int AlbumId { get; set; }
public string Title { get; set; }
public int TrackNumber { get; set; }
public IEnumerable<SelectListItem> Albums { get; set; }
}
扩展方法
public static IEnumerable<SelectListItem> ToSelectListItems(
this IEnumerable<Album> 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)
看看这个博客文章,解释这一切:
Take a look at this blog post that explains it all: