简体   繁体   English

ASP.NET MVC - 填充下拉列表

[英]ASP.NET MVC - Populate a drop down list

I'm new to ASP.NET MVC. 我是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: 在ASP.NET Web表单中,我知道我可以加载下拉列表,如下所示:

Page.aspx Page.aspx

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

Page.aspx.cs 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? 我如何在ASP.NET MVC中执行相同类型的操作? Thank you! 谢谢!

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 下拉列表和ASP.NET MVC

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM