ASP.NET: Loop Statements in WebMatrix and Razor

Posted by: Suprotim Agarwal , on 7/25/2011, in Category ASP.NET
Views: 109439
Abstract: Microsoft WebMatrix utilizes the new Razor syntax. All programming languages use the Loop constructs and the same goes for WebMatrix programming too. If you are new to the razor syntax, it could be confusing at times to remember programming constructs in Razor. This article aims at giving you a basic loop programming concept overview if you are using WebMatrix.

If you have been visiting this site regularly, you must be familiar with the free Microsoft WebMatrix tool which is a lightweight web development platform and helps you to create websites in different ways. This tool is primarily aimed at new developers as well as PHP/Ruby developers who are starting with web development using ASP.NET. However this article is also useful for devs using ASP.NET MVC and getting started with the Razor view engine.

Microsoft WebMatrix utilizes the new Razor syntax and everything in Razor begins with the @ symbol. For those who have programmed in ASP.NET earlier, the @ symbol is also a replacement for the <%…%> syntax. Now all programming languages use the Loop constructs and the same goes for WebMatrix programming too.  If you are new to the razor syntax, it could be confusing at times to remember programming constructs in Razor. This article aims at giving you a basic loop programming concept overview if you are using WebMatrix. This article assumes you have used loops in other programming languages. So roll up your sleeves and let us get started:

 

Note: Just make sure that you have read the article ASP.NET WebMatrix - Getting Started if you are new to WebMatrix and Razor.

 

For Loop Razor Syntax

If you know exactly how many times you want to loop, you use a ‘for’ loop. The for loop syntax is Razor is very simple and requires less typing when compared to the asp.net server side syntax. In razor, you would use a for loop as follows:

Razor for Loop

whereas in ASP.NET server-side syntax, the same would be written as

ASP.NET For Loop

As you can observe, the razor syntax is much simpler. The first statement (var i=0;) creates a counter and initializes it to 0.  When the for loop runs, the counter is automatically incremented. The second statement (i < 100) sets the condition for how far you want to run the loop. In our case, we want to go till 99. The third statement (i++ ) uses an increment operator, which adds one to the counter each time the loop runs.

The @i renders the variable number and prints it’s value. You can even use expressions here like (@i * 10) which multiplies the value of ‘i’ with 10.

 

Foreach Loop Razor syntax

The Foreach loop is used to loop through a collection of objects. Here’s an example of how to loop through the values in Request.Querystring using Foreach loop. The Request.QueryString gives collection of information about the querystring params in the current request.

Razor foreach

The foreach keyword is followed by parentheses where you declare a variable ‘str’ that represents a single item in the collection. It is followed by the ‘in’ keyword, followed by the collection you want to loop through – in our case the collection is Request.QueryString. In the body of the foreach loop, we are accessing the current item using the variable that you declared earlier i.e. @str.

However what if you want the code inside the foreach to be treated as content i.e. you want to avoid using an HTML element inside the code container block to print some text? Just use the @: character sequence to explicitly indicate that this line within our code block should be treated as content.

Razor foreach

 

While Loop Razor Syntax

The while loop is similar to the for loop with the difference being that it executes code as long as a condition is true, in our case, as long as cnt < 50 as shown below:

image

 

Switch-case statement Razor syntax

On a side note, if you are wondering how a switch-case statement is written is Razor, here’s the code. The switch-case statement is not a loop but is used when you have to test a large number of conditions. In this example however, we will test only a few conditions  for understanding purposes.

Razor switchcase

 

Well those were some basics needed to use Loops in Razor within ASP.NET Web Pages. We will see more of Razor in the forthcoming articles. Stay tuned!

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Deepak Choudhari on Monday, July 25, 2011 9:24 AM
There seems to be a syntax error in example provided for - Switch-case statement Razor syntax. There should be an ending parenthesis either after the Switch construct or the <p> tag.

@{ var condition = 1; var day = "";
  
switch(condition){
    case 1:
        day = "It's Monday";
        break;
    case 2:
        day = "It's Tuesday";
        break;
    case 3:
        day = "It's Wednesday";
        break;
    default:
        day = "default";
        break;
}
<p>Since it is a @day, enjoy the rest of the week</p>
} //End paranthesis here.
Comment posted by Visitor on Wednesday, March 14, 2012 11:26 AM
Nice explanation

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel