ASP.NET MVC - 填充一个下拉列表 [英] ASP.NET MVC - Populate a drop down list
本文介绍了ASP.NET MVC - 填充一个下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新来的ASP.NET MVC。我试图找出如何创建我的数据库中一个基本的下拉列表中的值。在ASP.NET Web表单,我知道我可以加载一个下拉列表是这样的:
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();
}
}
我如何做ASP.NET MVC同类型的东西?谢谢!
How do I do the same type of thing in ASP.NET MVC? Thank you!
推荐答案
型号
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)
看看这个博客文章,解释这一切:
Take a look at this blog post that explains it all:
这篇关于ASP.NET MVC - 填充一个下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文