[英]How to populate drop down list on other drop down list selected asp .net mvc
[英]ASP.NET MVC - Populate a drop down list
我是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中執行相同類型的操作? 謝謝!
模型
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)
看看這篇解釋它的博客文章:
在MVC2中,在視圖中使用<%=Html.DropListFor(x => x.MemberName, Model.DropListItems)%>
,在控制器中使用包含數據庫中項目的新SelectList
填充DropListItems。
我相信書呆子晚餐樣本包括這個,如果你是MVC的新手,你應該真的經歷並創建Nerd Dinner應用程序,因為你從中學到了很多東西,即使你打算不使用他們使用的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.