Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying dictionary values in View

I'm using C# asp.net with MVC and I just started so I am having a little trouble understanding how to pass a dictionary to the view and print out each value.

My dictionary looks like:

Dictionary<int, Dictionary<string, int>> values = new Dictionary<int, Dictionary<string, int>>();

What I would like is to have nested for each loops and print out:

firstInt   FirstString --valueInt
           SecondString--valueInt2
SecondInt  FirstString--valueInt3
           SecondString--valueInt4

etc.

Using C#, I would know how to do this as I would just go through the dictionaries and print out their values but I don't know how to do this in a view. The method that returns the dictionary is in the controller.

like image 977
mo alaz Avatar asked Apr 11 '26 19:04

mo alaz


1 Answers

Assuming Razor is your view engine, put the dictionary in the ViewBag and in your view, do something like:

@foreach (var item in ViewBag.MyDictionary) {
<ul>
    <li>@item.Key
    <ul>
    @foreach (var subItem in item.Value) {
        <li>@subItem.Key [email protected]</li>
    }
    </ul>
    </li>
</ul>
}
like image 159
mwrichardson Avatar answered Apr 13 '26 08:04

mwrichardson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!