asp.net-mvc – 如何在ASP.NET MVC视图中对HTML列表项进行分组?

我在视图中有这个代码
<ul>
    @foreach (var tag in Model)
    {
        <li><a href="/Post/Tag/@tag.Id">@tag.Name</a></li>
    }
</ul>

现在我需要按照第一个字符对List Items进行分组

A
 -Apple
 -Ant

C
 -Car

S
 -Sky
 -Sea
 -Sun

我怎样才能做到这一点?

解决方法

How can I achieve this?

好简单.答案,如asp.net-mvc标签中99.99%的问题总是相同的:使用视图模型.

我假设您有以下域模型:

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

因此,您始终要定义一个视图模型,该模型将满足您要在此视图中实现的要求(通过其Name属性的第一个字母对Tag域模型列表进行分组并显示链接):

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中的一些困难或问题时告诉自己:我必须使用视图模型.看,问题解决了.

相关文章

引言 本文从Linux小白的视角, 在CentOS 7.x服务器上搭建一个...
引言: 多线程编程/异步编程非常复杂,有很多概念和工具需要...
一. 宏观概念 ASP.NET Core Middleware是在应用程序处理管道...
背景 在.Net和C#中运行异步代码相当简单,因为我们有时候需要...
HTTP基本认证 在HTTP中,HTTP基本认证(Basic Authenticatio...
1.Linq 执行多列排序 OrderBy的意义是按照指定顺序排序,连续...