Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Populate a drop down list

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 like this:

Page.aspx

<asp:DropDownList ID="myDropDownList" runat="server" DataTextField="FullName" DataValueField="ID" OnLoad="myDropDownList_Load" />

Page.aspx.cs

void myDropDownList_Load(object sender, EventArgs e)
{
  if (Page.IsPostBack == false)
  {
    List<Person> people = GetPeopleFromDatabase();
    myDropDownList.DataSource = people;
    myDropDownList.DataBind();
  }
}

How do I do the same type of thing in ASP.NET MVC? Thank you!

like image 557
user70192 Avatar asked Mar 07 '10 16:03

user70192


2 Answers

Model

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

Extension method

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

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

like image 71
Leniel Maccaferri Avatar answered Sep 21 '22 17:09

Leniel Maccaferri


In MVC2, use <%=Html.DropListFor(x => x.MemberName, Model.DropListItems)%> in your view and in your controller you populate DropListItems with a new SelectList containing the items from the database.

I belive that the Nerd Dinner-sample includes this, and if you're new to MVC you should really really go through and create the Nerd Dinner app, because you learn so much from it, even if you plan to not use what they use.

like image 29
Svante Svenson Avatar answered Sep 20 '22 17:09

Svante Svenson