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

cod*_*ole 2 .net c# entity-framework asp.net-mvc-3 drop-down-menu

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

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

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

编辑1

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

   @model MvcMusicStore.Models.Album
<p> @Html.LabelFor(model => model.Genre) @Html.DropDownList("GenreId",
new SelectList(ViewBag.Genres as System.Collections.IEnumerable,
"GenreId", "Name", Model.GenreId))
</p>
<p> @Html.LabelFor(model => model.Artist) @Html.DropDownList("ArtistId",
new SelectList(ViewBag.Artists as System.Collections.IEnumerable,
"ArtistId", "Name", Model.ArtistId))
</p>
Run Code Online (Sandbox Code Playgroud)

我相信其中包括:

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);
}
Run Code Online (Sandbox Code Playgroud)

除了下拉列表没有填充之外我没有任何错误...

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

编辑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页面.无论如何所有现在都修好了,谢谢......

Dar*_*rov 13

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

public class AlbumViewModel
{
    public string GenreId { get; set; }
    public IEnumerable<Genre> Genres { get; set; }

    public string ArtistId { get; set; }
    public IEnumerable<Artist> Artists { get; set; }

    public Album Album { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

@model MvcMusicStore.Models.AlbumViewModel
<p> 
    @Html.LabelFor(model => model.GenreId) 
    @Html.DropDownListFor(x => x.GenreId, new SelectList(Model.Genres, "GenreId", "Name"))
</p>

<p> 
    @Html.LabelFor(model => model.ArtistId) 
    @Html.DropDownListFor(x => x.ArtistId, new SelectList(Model.Artists, "ArtistId", "Name"))
</p>
Run Code Online (Sandbox Code Playgroud)