Razor C# list and sublist with List<String> (originally "how to check if an HTML element already exists")

Asked

Viewed 1,174 times

4

I need to know if an HTML element already exists, in my loop, if it exists I use it, if it doesn’t exist I create a.

How would you do it inside a

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

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

  • I have a List<String> alphabetically ordered.
  • All strings starting with A I want you to stay below a <li>A</li>

I want a <ul> with the <li>s organized that way. Someone has some hint?

I need it dynamic because it’s always changing values.

  • Razor does not evaluate HTML elements: only elements within MVC. I think it is impossible to do what you want.

  • So as it is not possible I edited the question by putting another possible solution. Thank you.

  • Much better. Now I can answer.

1 answer

4


I’m guessing that Model is List<String>, then I can sort alphabetically and group the 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.