Reader small image

You're reading from  Instant Razor View Engine How-to

Product typeBook
Published inMay 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781849696302
Edition1st Edition
Languages
Concepts
Right arrow
Author (1)
Abhimanyu Kumar Vatsa
Abhimanyu Kumar Vatsa
author image
Abhimanyu Kumar Vatsa

Abhimanyu Kumar Vatsa works at Coxtan College, located in Bokaro Steel City, India as a lecturer focused on web technologies. He is a Microsoft MVP in ASP.NET/IIS. He loves to blog and started blogging in June 2009. He holds a bachelor's degree in Computer Science and Applications, a master's degree in Information Technology, and a few application-level diplomas. He moved to Bokaro Steel City from a remote village to pursue higher education in March 2003, and that was when he saw a computer with Windows 95 OS on Pentium 1 for the first time, and since then, he has never looked back.
Read more about Abhimanyu Kumar Vatsa

Right arrow

Fundamental Razor syntaxes (Must know)


In this recipe we will go and look at inline, code block and mixed expressions; and some fundamental Razor syntaxes such as conditional statements, loops, and comments.

Getting ready

In the Creating the project (Should know) recipe, we created a project using the Internet Application template with the Razor view engine and added a Demo controller and an Index.cshtml view page. In this view page you can try all the Razor syntaxes given in this recipe.

How to do it...

Here, let's start learning the fundamental Razor syntaxes. All Razor syntaxes can be written using three different approaches: inline, code block, and mixed.

Inline code expressions

Inline code expressions are always written in a single line, as follows:

I always enjoy @DateTime.Now.DayOfWeek with my family.

At runtime, the inline code expression, which is @DateTime.Now.DayOfWeek, will be converted into a day, such as Sunday. This can be seen in the following screenshot:

Let's look at one more example, which will pass the controller's ViewBag and ViewData messages on the view.

The rendered output will be as follows:

Code block expression

Code block expression is actually a set of multiple code lines that start and end with @{}. The use of opening (@{) and closing (}) characters is mandatory, even for single line of C# or VB code; as shown in the following screenshot:

This will render the following output:

Mixed code expression

Mixed code expression is a set of multiple inline code expressions in a code block where we switch between C# and HTML. The magical key here is @:, which allows writing HTML in a code block, as follows:

This will render the following output:

So, this is all about how we write the code on Razor view page. You learned all these three approaches with examples, let's move on now.

We can see the conditional statements (also known as conditional expressions) being in programming languages such as C#, VB, C, C++, and Java. The good part is that Razor supports writing conditional statements, let's learn them all. I am not going to discuss what all these conditional statements can do or what are the differences, I'll just show you a quick example on each of them:

  • The if statement

    In the preceding screenshot, I wrapped every code inside a single code block expression that starts and ends with @{}. So, when one uses this syntax, there is no need to use an @ before the if condition, as the following example:

    <p>
        @{
            string day = DateTime.Now.DayOfWeek.ToString();
        }
        @if(day == "Sunday")
        {
            @:I enjoy @day with my family.
        }
    </p>
  • The if-else statement

  • The if-else if-else statement

    That's all you need to know about the simple conditional statements. Try it out yourself, it works great. You will feel like writing C# conditional statements all day.

    We can also use ternary operators in Razor. If you have a condition that can be checked as an if situation with one alternate else, you can use the ternary operator that is a combination of ? and : characters. Here is an example showing the use of ternary operators:

    I think things are much clear to you now that you know how to write conditional statements using Razor syntax. Let's go ahead and learn looping in Razor.

    Looping is another essential ability to repeat a block of code a defined number of times. In C#, they come in different variants and Razor supports all; let's look at a few examples.

  • The for loop

    The for loop is a bit different. It's better when you know how many iterations you want, either because you know the exact amount of iterations, or because you have a variable containing the amount.

  • The foreach loop

    The foreach loop operates on collections of items, for instance, list/array or another built-in collection type.

    In preceeding loop example, I have used code block expressions, however, this can be done using inline code expression also, as follows:

  • The while loop

    The while loop simply executes a block of code as long as the condition you give it is true.

  • The dowhile loop

    The dowhile loop evaluates the condition after the loop has executed, which makes sure that the code block is always executed at least once.

So, that's all you need to know about looping using Razor syntaxes. Now you understand how simple Razor syntax is, keep reading.

Unlike C# and VB, we can also comment the Razor syntax, which is also essential to learn. Let's learn them.

The comments in Razor are always delimited by @* and *@. This can be seen in the following screenshot:

If you are inside a code block, you can also use // and /* */ comment delimiters, shown as follows:

That's all about the commenting options available in Razor, let's move on and learn about the <text> tag.

In some situations you need to write HTML inside code block expressions and wish to display content for better identification, you could do this using the <text> tag. Here is an example which will wrap a multi-line content:

Look at the HTML source code in the preceding screenshot; it does not include any wrapping tags. Optionally, we can wrap the content with a tag such as <span>, but this will display the <span> tag in the HTML source code as shown in the following screenshot:

We also have a Razor language parser that enables us to do some heavy lifting. For example, to display the e-mail ID and Twitter handler on a web page, the Razor language parser works cleverly in most cases to infer whether a @ character within a template is used for the code or static content. Take a look at the following example:

For my e-mail ID, the @ character works cleverly, but for my Twitter handler it didn't. In this case, I can explicitly escape out the @ characters by typing @@; the following screenshot shows you how:

Here is another parsing. You should know here that I am trying to divide the total, which is an integer variable containing 500, by 5, but it is actually concatenating the string instead of dividing.

To overcome this issue, I need to make it an explicit code expression by putting code inside parentheses like (total/5).

And now we see that it works fine.

That's all you need to know about the fundamental Razor syntaxes. Now you are all set to dig deeper into the Razor view engine.

Previous PageNext Page
You have been reading a chapter from
Instant Razor View Engine How-to
Published in: May 2013Publisher: PacktISBN-13: 9781849696302
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Abhimanyu Kumar Vatsa

Abhimanyu Kumar Vatsa works at Coxtan College, located in Bokaro Steel City, India as a lecturer focused on web technologies. He is a Microsoft MVP in ASP.NET/IIS. He loves to blog and started blogging in June 2009. He holds a bachelor's degree in Computer Science and Applications, a master's degree in Information Technology, and a few application-level diplomas. He moved to Bokaro Steel City from a remote village to pursue higher education in March 2003, and that was when he saw a computer with Windows 95 OS on Pentium 1 for the first time, and since then, he has never looked back.
Read more about Abhimanyu Kumar Vatsa