且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC - 填充一个下拉列表

更新时间: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:

下拉列表和ASP.NET MVC