Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through models content in Razor

I want to loop through each item in my model in my razor view but I want to group all items together. I then want to loop through each group. Imagine I have a table:

ID   GroupNo    GroupName
1    1          Group1
2    1          Group2
3    1          Group3
4    2          Group1
5    2          Group2
6    3          Group56

I want to do something like:

@foreach (var group in Model.GroupNo) {
    <section>
        <header>Group No is @group.GroupNo</header>
        @foreach (var item in group) {
            <p>GroupName: @item.GroupName</p>
        }
    </section>
} 

So my output is:

Group No is 1
GroupName: Group1
GroupName: Group2
GroupName: Group3
Group No is 2
GroupName: Group1
GroupName: Group2
Group No is 3
GroupName: Group56

Is this possible?

Thanks

like image 885
Rodders Avatar asked Oct 25 '12 23:10

Rodders


People also ask

How do you loop through a model?

To loop through Model items in ASP.NET MVC view, use foreach loop in the Controller,which returns Collection of items. Add the given below line to bind your model with . cshtml page. Now write foreach loop at view level page(.

What is foreach loop in MVC?

Generally, the loops in asp.net mvc razor view will work same as other programming languages. We can define the loop inside or outside the code block in razor, and we can use the same foreach looping concept to assign value to define the condition.

What is @model in razor?

New @model directive Let's now look at a new feature we added with the ASP.NET MVC 3 Beta – the @model directive. The @model directive provides a cleaner and more concise way to reference strongly-typed models from view files.


1 Answers

Yes, this is easy to do using the Linq GroupBy. I'd suggest changing your view to use @model IEnumerable<IGrouping<string, MyModel>>, which you'd populate like this:

var groupModel = MyModelCollection.GroupBy(item => item.GroupNo).ToArray();
return View(groupModel);

Then, simply iterate through the group as you wrote, except using group.Key instead of group.GroupNo to retrieve IGrouping's key:

@foreach (var group in Model) {
    <section>
        <header>Group No is @group.Key</header>
        @foreach (var item in group) {
            <p>GroupName: @item.GroupName</p>
        }
    </section>
} 
like image 120
McGarnagle Avatar answered Oct 05 '22 17:10

McGarnagle