Foreach loop in ASP.NET MVC Razor

By Mar 06, 2016

Description:

We explain how to use For loop in ASP.NET MVC Razor engine with multiple examples. For loop can be used in a C# block or preceded by a @ in the HTML code.

Preferencesoft

In this article, we explain how to use the foreach loop statement in MVC Razor engine and give several examples. Like the others loop statements, foreach is used to repeat a instruction block. In a .cshtml page, a foreach loop can be used to generate HTML code, forming lists, tables, grids etc.

Foreach loop

The foreach statement allows you to repeat instruction sequence for each element in a collection. A variable iterates through a collection and automatically takes each of the values by respecting the order of the elements. Unlike for loop, when used on a collection, one does not have to vary an index pointing to each element of the collection.

Iterating through a string

The foreach statement is used to iterate through a string:

<ul>
     @foreach (var c in "abcd")
    {
        <li>@c</li>
    }
</ul>

Output:

  • a
  • b
  • c
  • d

Iterating through an array

Now let's give some examples of iteration through an array:

@{ string[] strArray = { "Steeve", "John" }; }
<ol>
    @foreach (var name in strArray)
    {
        <li>@name</li>
    }
</ol> 

Output:

  1. Steeve
  2. John
@{string[,] table = { { "t11", "t12", "t13" }, { "t21", "t22", "t23" } }; }
<ol>
    @foreach (var name in table)
    {
        <li>@name</li>
    }
</ol>

Output:

  1. t11
  2. t12
  3. t13
  4. t21
  5. t22
  6. t23
<ol>
    @{string[,] t = { { "a11", "a12" }, { "a21", "a22" }, { "a31", "a32" } };
        string[] a = new string[t.Length];
        int i = 0;
        //Copying in a one-dimensional array 
        foreach (var elem in t)
        {
            a[i++] = elem;
        }
        Array.Reverse(a);
    }
    @foreach (var elem in a)
    {
        <li>@elem</li>
    }
</ol>

Output:

  1. a32
  2. a31
  3. a22
  4. a21
  5. a12
  6. a11
@{string[][] array2 = { new string[] { "a11", "a12", "a13" }, new string[] { "a21", "a22", "a23" } }; }
@foreach (int line in new int[] { 0, 1 })
{
    @:<div class="btn-group" role="group" aria-label="...">
        foreach (var col in array2[line])
    {
        <button type="button" class="btn btn-default">@col</button>
    }
    @:</div>
    @:<br />
}

Output:


Iterating through a List

We can also iterate through a list:

@{
    List<string> ls = new List<string>() { "l1", "l3", "l8", "l9" };
    @:<ol>
        foreach (string elem in ls)
        {
        @:<li>@elem</li>

        }
    @:</ol>
}

Output:

  1. l1
  2. l3
  3. l8
  4. l9

ASP.NET

Categories

Share

Follow


KodFor Privacy Policy