asp.net-mvc – 如何在ASP.NET MVC视图中对HTML列表项进行分组?
发布时间:2020-05-23 19:58:10 所属栏目:asp.Net 来源:互联网
导读:我在视图中有这个代码 ul @foreach (var tag in Model) { lia href=/Post/Tag/@tag.Id@tag.Name/a/li }/ul 现在我需要按照第一个字符对List Items进行分组 A -Apple -AntC -CarS -Sky -Sea -Sun 我
|
我在视图中有这个代码 <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 我怎样才能做到这一点? 解决方法
好简单.答案,如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中的一些困难或问题时告诉自己:我必须使用视图模型.看,问题解决了. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ASP.NET元:resourcekey
- ASP.NET – 可以从服务器代码触发回发吗?
- asp.net-mvc – MVC4 Web Api中的[Bind(Prefix =“principa
- ASP.NET C#中的自定义控件
- asp.net – ELMAH登录SQL Server
- asp.net – SOAP与HTTP
- asp.net – Gridview编辑,点击两次问题
- asp.net-mvc – ASP.NET MVC用户友好401错误
- asp.net-mvc – 程序集使用System.Web.Http 5.1,它比引用的
- asp.net-mvc – 如何在ASP.NET Web API中获取IpAddress和Us
推荐文章
站长推荐
- asp.net-mvc – 实体框架4不保存我的多对多行
- asp.net-mvc – ScriptBundle中的{version}是什么
- asp.net-mvc-4 – Kendo UI组合框复位值
- ASP.NET MVC 3:添加控制器时自动生成视图(无实体
- asp.net-mvc – ASP.NET MVC切换语言,如何实现?
- asp.net-2.0 – 如何在生产环境中删除临时ASP.ne
- asp.net – 如何通过web.config文件中的Access-C
- asp.net-mvc – 缓存的最佳解决方案
- asp.net-mvc – 如何使用MVC3 Razor布局页面?
- asp.net – Intranet / Internet的Windows身份验
热点阅读
