7

我在视图中有这段代码

<ul>
    @foreach (var tag in Model)
    {
        <li><a href="/Post/Tag/@tag.Id">@tag.Name</a></li>
    }
</ul>

现在我需要按第一个字符对列表项进行分组,比如

A
 -Apple
 -Ant

C
 -Car

S
 -Sky
 -Sea
 -Sun

我怎样才能做到这一点?

4

1 回答 1

27

我怎样才能做到这一点?

好简单。答案,就像asp.net-mvc标签中 99.99% 的问题一样:使用视图模型

我假设您具有以下域模型:

public class Tag
{
    public int Id { get; set; }
    public string Name { get; set; }
}

因此,与往常一样,您首先定义一个视图模型,该模型将满足您要在此视图中实现的要求(按属性Tag的第一个字母对域模型列表进行分组Name并显示一个链接):

public class TagViewModel
{
    public string Letter { get; set; }
    public IEnumerable<Tag> Tags { get; set; }
}

那么您显然将拥有一个控制器,其职责是查询您的 DAL 层以获取域模型、构建视图模型并最终将此视图模型传递给视图:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // Get the domain model
        var tags = new[]
        {
            // Guess this comes from a database or something
            new Tag { Id = 1, Name = "Apple" },
            new Tag { Id = 2, Name = "Ant" },
            new Tag { Id = 3, Name = "Car" },
            new Tag { Id = 4, Name = "Sky" },
            new Tag { Id = 5, Name = "Sea" },
            new Tag { Id = 6, Name = "Sun" },
        };

        // now build the view model:
        var model = tags.GroupBy(t => t.Name.Substring(0, 1)).Select(g => new TagViewModel
        {
            Letter = g.Key,
            Tags = g
        });

        return View(model);
    }
}

最后是一个观点:

@model IEnumerable<TagViewModel>

@foreach (var item in Model)
{
    <h2>@item.Letter</h2>
    <ul>
        @foreach (var tag in item.Tags)
        {
            <li>
                <!-- Please notice the usage of an HTML helper to generate
                     the anchor instead of the hardcoded url shown in your
                     question which is very bad
                -->
                @Html.ActionLink(
                    tag.Name, 
                    "Post", 
                    "Tag", 
                    new { id = tag.Id }, 
                    null
                )
            </li>
        }
    </ul>
}

这显然会给出预期的结果:

在此处输入图像描述

所以下次你在 ASP.NET MVC 中遇到一些困难或问题时,请告诉自己:我必须使用视图模型。看,问题解决了。

于 2012-07-07T17:38:32.997 回答