How to group HTML list items in ASP.NET MVC view?

I have this code in view

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

Now I need to group the list items with my first character, for example

A
 -Apple
 -Ant

C
 -Car

S
 -Sky
 -Sea
 -Sun

How can i achieve this?

+5
source share
1 answer

How can i achieve this?

Very easy. The answer, as in 99.99% of the questions in the asp.net-mvc tag , is always the same: use view models .

I assume that you have the following domain model:

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>
}

, , :

enter image description here

, , ASP.NET MVC, : . ., .

+22