填充ASP.NET MVC 3应用程序中的下拉框的问题

我已经在www.asp.net上完成了关于MVC 3的新教程(音乐商店)。 一切都很顺利,除了应该从数据库中填充两个下拉框的部分 – 而它们不是。

我按照教程并双重检查了我的代码。 我认为问题可能是使用editorstemplate文件夹。 因为我是MVC的新手,所以不知道。 那么问题是什么,或者我该如何调试呢?

==============

编辑1

好的所以这里是album.cshtml的一些代码,它位于/ views / shared / editortemplates /文件夹中

@model MvcMusicStore.Models.Album 

@Html.LabelFor(model => model.Genre) @Html.DropDownList("GenreId", new SelectList(ViewBag.Genres as System.Collections.IEnumerable, "GenreId", "Name", Model.GenreId))

@Html.LabelFor(model => model.Artist) @Html.DropDownList("ArtistId", new SelectList(ViewBag.Artists as System.Collections.IEnumerable, "ArtistId", "Name", Model.ArtistId))

我相信其中包括:

 public ActionResult Edit(int id) { ViewBag.Genres = storeDB.Genres.OrderBy(g => g.Name).ToList(); ViewBag.Artists = storeDB.Artists.OrderBy(a => a.Name).ToList(); var album = storeDB.Albums.Single(a => a.AlbumId == id); return View(album); } 

除了未填充下拉菜单之外,我没有任何错误…

==============

编辑2

所以我在/views/storemanager/edit.cshtml中有edit.cshtml,然后我在/views/shared/editortemplates/album.cshtml中有了album.cshtml。 下拉列表应该从album.cshtml填充到edit.cshtml中。 我将album.cshtml中的代码直接放到edit.cshtml中,它运行正常。 所以我认为问题是editortemplates / album.cshtml无效,即填充edit.cshtml页面。 什么赋予了什么? 谢谢…

==============

编辑3

好的,我发现了问题,我从CodePlex获得了工作源。 好像我没有正确设置create.cshtml和edit.cshtml页面。 无论如何所有现在都修好了,谢谢……

我建议你使用视图模型,避免使用任何ViewBag 。 首先,您要定义一个视图模型:

 public class AlbumViewModel { public string GenreId { get; set; } public IEnumerable Genres { get; set; } public string ArtistId { get; set; } public IEnumerable Artists { get; set; } public Album Album { get; set; } } 

然后在控制器操作中填充此视图模型:

 public ActionResult Edit(int id) { var model = new AlbumViewModel { Genres = storeDB.Genres.OrderBy(g => g.Name), Artists = storeDB.Artists.OrderBy(a => a.Name), Album = storeDB.Albums.Single(a => a.AlbumId == id) }; return View(model); } 

最后在你的编辑器模板中( ~/Views/Shared/EditorTemplates/AlbumViewModel.cshtml ):

 @model MvcMusicStore.Models.AlbumViewModel 

@Html.LabelFor(model => model.GenreId) @Html.DropDownListFor(x => x.GenreId, new SelectList(Model.Genres, "GenreId", "Name"))

@Html.LabelFor(model => model.ArtistId) @Html.DropDownListFor(x => x.ArtistId, new SelectList(Model.Artists, "ArtistId", "Name"))

好的,我发现了问题,我从CodePlex获得了工作源。 好像我没有正确设置create.cshtml和edit.cshtml页面。 无论如何所有现在都修好了,谢谢……