use*_*192 8 c# asp.net-mvc populate drop-down-menu
我是ASP.NET MVC的新手.我正在试图弄清楚如何从我的数据库中的值创建一个基本的下拉列表.在ASP.NET Web表单中,我知道我可以加载下拉列表,如下所示:
Page.aspx
<asp:DropDownList ID="myDropDownList" runat="server" DataTextField="FullName" DataValueField="ID" OnLoad="myDropDownList_Load" />
Run Code Online (Sandbox Code Playgroud)
Page.aspx.cs
void myDropDownList_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
List<Person> people = GetPeopleFromDatabase();
myDropDownList.DataSource = people;
myDropDownList.DataBind();
}
}
Run Code Online (Sandbox Code Playgroud)
我如何在ASP.NET MVC中执行相同类型的操作?谢谢!
模型
public class EditSongViewModel
{
public int AlbumId { get; set; }
public string Title { get; set; }
public int TrackNumber { get; set; }
public IEnumerable<SelectListItem> Albums { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
扩展方法
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()
});
}
Run Code Online (Sandbox Code Playgroud)
从数据库中获取数据
model.Albums = _repository.FindAllAlbums().ToSelectItems(selectedId);
Run Code Online (Sandbox Code Playgroud)
视图
@Html.DropDownList("AlbumId", Model.Albums)
Run Code Online (Sandbox Code Playgroud)
或者更好的是:
@Html.DropDownListFor(model => model.AlbumId, Model.Albums)
Run Code Online (Sandbox Code Playgroud)
看看这篇解释它的博客文章:
在 MVC2 中,<%=Html.DropListFor(x => x.MemberName, Model.DropListItems)%>
在视图和控制器中使用包含SelectList
数据库中项目的新内容填充 DropListItems。
我相信 Nerd Dining 示例包含此内容,如果您是 MVC 新手,您真的应该仔细阅读并创建 Nerd Dining 应用程序,因为您可以从中学到很多东西,即使您打算不使用他们使用的东西。
归档时间: |
|
查看次数: |
21907 次 |
最近记录: |