Razor C # make list and sublist with ListString (originally "how to check if an HTML element already exists")

4

I need to know if an HTML element already exists, in my loop, if it exists I use it, if it does not exist I'll create one.

How would you do this within a

@foreach (var item in Model){ ... }

Following the comment of Gypsy, as it is not possible I wanted a logic like this:

  • I have List<String> sorted alphabetically.
  • All strings that begin with A I want them to be below a <li>A</li>

I want a <ul> with <li> s organized in this way. Anyone have any tips?

I need this dynamic because it is always changing values.

    
asked by anonymous 13.05.2015 / 01:28

1 answer

4

I'm assuming that Model is List<String> , so I can alphabetically sort and group values by the first letter of each String :

<ul>
@foreach (var item in Model.OrderBy(s => s).GroupBy(s => s[0])) 
{
    <li>
        @item.Key
        @if (item.ToList().Count > 0) {
        <ul>
            @foreach (var subitem in item.ToList()) 
            {
                <li>@subitem</li>
            }
        </ul>
        }
    </li>
}
</ul>
    
13.05.2015 / 02:03