ASP.NET MVC - Populate a drop down list

前端 未结 2 1258
执念已碎
执念已碎 2020-12-31 20:35

I\'m new to ASP.NET MVC. I\'m trying to figure out how create a basic drop down list from values in my database. In ASP.NET web forms, I know I can load a drop down list lik

2条回答
  •  一向
    一向 (楼主)
    2020-12-31 21:20

    Model

    public class EditSongViewModel
    {        
        public int AlbumId { get; set; }
        public string Title { get; set; }                
        public int TrackNumber { get; set; }
        public IEnumerable Albums { get; set; }
    }
    

    Extension method

    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()
                       });
    }
    

    Getting data from database

    model.Albums = _repository.FindAllAlbums().ToSelectItems(selectedId);
    

    View

    @Html.DropDownList("AlbumId", Model.Albums)
    

    or better yet:

    @Html.DropDownListFor(model => model.AlbumId, Model.Albums)
    

    Take a look at this blog post that explains it all:

    Drop-down Lists and ASP.NET MVC

提交回复
热议问题