ASP.NET MVC - 填充下拉列表

时间:2010-03-07 16:02:31

标签: c# asp.net-mvc drop-down-menu populate

我是ASP.NET MVC的新手。我正在试图弄清楚如何从我的数据库中的值创建一个基本的下拉列表。在ASP.NET Web表单中,我知道我可以加载这样的下拉列表:

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

如何在ASP.NET MVC中执行相同类型的操作?谢谢!

2 个答案:

答案 0 :(得分:8)

<强>模型

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)

看看这篇解释一切的博文:

Drop-down Lists and ASP.NET MVC

答案 1 :(得分:2)

在MVC2中,在视图和控制器中使用<%=Html.DropListFor(x => x.MemberName, Model.DropListItems)%>,使用包含数据库中项目的新SelectList填充DropListItems。

我相信书呆子晚餐样本包括这个,如果你是MVC的新手,你应该真的经历并创建Nerd Dinner应用程序,因为你从中学到了很多东西,即使你打算不使用它他们用什么。