如何在ASP.NET MVC视图中对HTML列表项进行分组? [英] How do I group HTML List Items in an ASP.NET MVC View?
问题描述
我在视图中有此代码
<ul>
@foreach (var tag in Model)
{
<li><a href="/Post/Tag/@tag.Id">@tag.Name</a></li>
}
</ul>
现在我需要按列表项的第一个字符进行分组,例如
now I need to group List Items by its first character, like
A
-Apple
-Ant
C
-Car
S
-Sky
-Sea
-Sun
我该如何实现?
推荐答案
我该如何实现?
How can I achieve this?
非常容易.答案就像 asp.net-mvc 标记中99.99%的问题一样相同:使用视图模型.
Very easy. The answer, as in the 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
属性的首字母分组,并显示一个链接):
So as always you start by defining a view model that will meet the requirements you want to implement in this view (which is grouping a list of Tag
domain models by the first letter of their Name
property and display a link):
public class TagViewModel
{
public string Letter { get; set; }
public IEnumerable<Tag> Tags { get; set; }
}
那么您显然将拥有一个控制器,其职责是查询您的DAL层以获取域模型,构建视图模型并将该视图模型最终传递给视图:
then you will obviously have a controller whose responsibility is to query your DAL layer in order to fetch the domain model, build a view model and finally pass this view model to the view:
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>
}
这显然会给出期望的结果:
which will obviously give the desired result:
因此,下次您在ASP.NET MVC中遇到一些困难或问题时,请告诉自己:我必须使用视图模型.看,问题解决了.
So next time you encounter some difficulty or problem in ASP.NET MVC tell to yourself: I must use a view model. See, problem solved.
这篇关于如何在ASP.NET MVC视图中对HTML列表项进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!