将搜索引擎添加到MVC音乐商店

时间:2013-08-01 16:13:07

标签: asp.net-mvc razor

我正在尝试在mvc音乐商店的商店内添加搜索标题加流派下拉列表。这是我已经完成的程序

首先我将以下代码添加到StoreManagere控制器

public ActionResult SearchIndex(string musicGenre, string searchString)
    {

        var GenreLST = new List<string>();

        var GenreQry = from d in db.Genres
                       orderby d.Name
                       select d.Name;

        GenreLST.AddRange(GenreQry.Distinct());
        ViewBag.movieGenre = new SelectList(GenreLST);

        var musics = from m in db.Albums.Include(a => a.Genre).Include(a => a.Artist)
                     select m;

        if (!string.IsNullOrEmpty(searchString))
        {
            musics = musics.Where(s => s.Title.Contains(searchString));
        }

        if (string.IsNullOrEmpty(musicGenre))
            return View(musics);
        else
        {
            return View(musics.Where(x => x.Genre.Name == musicGenre));
        }

    }

以及搜索索引视图页面中的以下代码

    @model IEnumerable<MvcMusicStore.Models.Album>


@{
    ViewBag.Title = "SearchIndex";

}

<h2>SearchIndex</h2>

<p>
    @Html.ActionLink("Create New", "Create")

    @using (Html.BeginForm()) {
            <p>Genre : @Html.DropDownList("musicGenre", "All")
            Title : @Html.TextBox("searchString")
            <input type="submit" value="Filetr" /></p>
    }
</p>
<table>
    <tr>
        <th>
            Genre
        </th>
        <th>
            Artist
        </th>
        <th>
            Title
        </th>
        <th>
            Price
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Genre.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Artist.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |
            @Html.ActionLink("Details", "Details", new { id=item.AlbumId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })
        </td>
    </tr>
}

</table>

但我收到此错误

  

没有“IEnumerable”类型的ViewData项具有“musicGenre”键。

1 个答案:

答案 0 :(得分:1)

您在ViewBag.movi​​eGenre中保存了您的流派列表,而不是musicGenre。这就是它无法正常工作的原因。

相关问题