我该如何做到这一点?
很简单。答案如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层Odel等,建立一个视图模型并最终通过这个视图模型的视图:
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中遇到一些困难或问题时请告诉自己:我必须使用视图模型。看,问题解决了。
非常感谢您的好回答....! :) – Nalaka526 2012-07-08 02:10:34