I have this code in a 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?
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:
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 theirName
property and display a link):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:
and finally a view:
which will obviously give the desired result:
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.