8

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

页面.aspx

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

页面.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 中做同样类型的事情?谢谢!

4

2 回答 2

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)

看看这篇解释了这一切的博客文章:

下拉列表和 ASP.NET MVC

于 2010-03-07T17:09:28.987 回答
2

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

我相信 Nerd Dinner-sample 包含这个,如果你是 MVC 新手,你真的应该去创建 Nerd Dinner 应用程序,因为你从中学到了很多东西,即使你打算不使用他们使用的东西.

于 2010-03-07T16:08:11.683 回答