Foreach Loop in Asp.Net MVC Razor View Engine Example

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.

Syntax of Foreach Loop in MVC Razor View 

Following is the syntax of using a foreach loop in asp.net mvc razor view.

 

foreach (var item in marks)

{

 

//Code Block

 

}

 

Example of Foreach Loop in MVC Razor View

Following is the example of using a foreach loop in asp.net mvc razor view.

 

<h2>ForEach loop</h2>

 

Output:-<br/>

 

@{

var marks = Enumerable.Range(0,5);

 

foreach (var item in marks)

{

@item<br/>

}

 

}

 

Output of Foreach Loop in MVC

Following is the result of the foreach loop example in asp.net mvc razor view engine.

 

foreach loop example in asp.net mvc razor view