MVC过滤A-Z

时间:2011-08-18 09:23:00

标签: asp.net asp.net-mvc asp.net-mvc-3

我已经从教程中创建了MVC音乐商店并且正在编辑它并添加新功能,最近我使浏览商店页面从A-Z链接到最后的All按钮。 我怎么能提出一条消息,上面写着“没有艺术家以字母A,B,C开头”,或者没有艺术家点击任何字母。

以下是我的商店索引中的代码:

@model IEnumerable<MVCMusicStore.Models.Artist>
@{
    ViewBag.Title = "Store";
}

<h3>Browse Artists</h3>
@Html.ActionLink("A", "Index", new { letter = "A" })
@Html.ActionLink("B", "Index", new { letter = "B" })
@Html.ActionLink("C", "Index", new { letter = "C" })
@Html.ActionLink("D", "Index", new { letter = "D" })
@Html.ActionLink("E", "Index", new { letter = "E" })
@Html.ActionLink("F", "Index", new { letter = "F" })
@Html.ActionLink("G", "Index", new { letter = "G" })
@Html.ActionLink("H", "Index", new { letter = "H" })
@Html.ActionLink("I", "Index", new { letter = "I" })
@Html.ActionLink("J", "Index", new { letter = "J" })
@Html.ActionLink("K", "Index", new { letter = "K" })
@Html.ActionLink("L", "Index", new { letter = "L" })
@Html.ActionLink("M", "Index", new { letter = "M" })
@Html.ActionLink("N", "Index", new { letter = "N" })
@Html.ActionLink("O", "Index", new { letter = "O" })
@Html.ActionLink("P", "Index", new { letter = "P" })
@Html.ActionLink("Q", "Index", new { letter = "Q" })
@Html.ActionLink("R", "Index", new { letter = "R" })
@Html.ActionLink("S", "Index", new { letter = "S" })
@Html.ActionLink("T", "Index", new { letter = "T" })
@Html.ActionLink("U", "Index", new { letter = "U" })
@Html.ActionLink("V", "Index", new { letter = "V" })
@Html.ActionLink("W", "Index", new { letter = "W" })
@Html.ActionLink("X", "Index", new { letter = "X" })
@Html.ActionLink("Y", "Index", new { letter = "Y" })
@Html.ActionLink("Z", "Index", new { letter = "Z" })
@Html.ActionLink("All", "Index", new { letter = "all" })


<ul>
    @foreach (var artist in Model)
    {
        <li>@Html.ActionLink(artist.Name,
"Browse", new { id = artist.ArtistId })</li>
    }
</ul>

这是我的控制器代码:

    public ActionResult Index(string letter = "")
    {
        IEnumerable<Artist> artist;

        if (letter == "all")
        {
            artist = storeDB.Artists.OrderBy(x =>x.Name).ToList();
        }
        else if (letter != "")
        {
artist = storeDB.Artists.Where(a => a.Name.StartsWith(letter)).OrderBy(x => x.Name).ToList();
        }
        else
        {
            artist = new List<Artist>();
        }

2 个答案:

答案 0 :(得分:2)

要使您的视图更整洁,您可以使用:

@for (int y = 0; y < 27; y++) {
    char filter = Convert.ToChar(65 + y);
    string letter = filter.toString();

    if(y == 27){       
      letter = "All";
    }

    @Html.ActionLink(letter, "Index", new { letter = letter  });
}

这将保存所有这些操作链接

答案 1 :(得分:1)

@if(Model.Any())
{
    foreach (var artist in Model)
    {
        <li>@Html.ActionLink(artist.Name,
"Browse", new { id = artist.ArtistId })</li>
    }
}
else
{
    <span>There are no artists</span>
}