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. In razor we can define loop inside or outside code block and we can use same foreach looping concept to assign value, define condition.

Syntax of Foreach Loop in MVC Razor View 

Following is the syntax of using 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 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 foreach loop example in asp.net mvc razor view engine

 

foreach loop example in asp.net mvc razor view