What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 19691 |  Welcome, Guest!   Register  Login
Home > Articles > HTML 5 > Introduction to Razor

Introduction to Razor

1 vote(s)
Rating: 5 out of 5
Article posted by Vuyiswamb on 7/29/2012 | Views: 3704 | Category: HTML 5 | Level: Beginner | Points: 250 red flag


In this Article you will learn the Basics of Razor and How to use it

Introduction

This is my first article for this year. I have been very busy with other things and I have not abandoned my work as an evangelist in technology. This article will differ a bit to my beliefs , I know most of you expect a Silverlight kind of article , but now I need to introduce some different to you.

In this article I am going to introduce you to building Data driven websites using Razor and in this introduction article I will give you the basic info on Razor. 

What is Razor ?

Razor is a template syntax that allows you to combine code and content in one place and in an expressive  manner. Though it introduces a few symbols and keywords, Razor is not a New language. Instead, Razor lets you write code using languages you probably already Know, such as C# or Visual Basic .NET. This means you can write a C# code and let HTML compliment it and also the other way around. 


Examples on Razor

Razor’s learning curve is very short, as it lets you work with your existing skills rather than requiring you to learn an entirely new language. Therefore, if you know how to write HTML and make a .NET API call, you can easily write mark-up like the following:

This page rendered at @DateTime.Now

which renders something like this:

This page rendered at 12/7/1941 7:38:00 AM

The above example begins with a standard HTML tag (the <div> tag), followed by a bit of static text. In the midst of all of this is some dynamic text rendered via a call to the .NET System.DateTime object, followed by the closing (</div>) tag. Razor’s intelligent parser allows developers to be more expressive with their logic and make easier transitions between code and mark-up.


Code Nuggets

Code nuggets are simple expressions that are evaluated and rendered inline. They can be mixed with text and look like this:

Not Logged In: @Html.ActionLink("Login", "Login")

The expression begins immediately after the @ symbol, and Razor is smart enough to know that the closing parenthesis indicates the end of this particular statement. The previous example will render this output:

Not Logged In: Login

Notice that code nuggets must always return markup for the view to render. If you write a code nugget that does not return anything (i.e. returns void), you will receive an error when the view executes.


Code Blocks

A code block is a section of the view that contains strictly code rather than a combination of markup and code. Razor defines a code block as any section of a Razor template wrapped in @{ } characters. The @{ characters mark the beginning of the block,

followed by any number of lines of code. The } character closes the code block. Keep in mind that the code within a code block is not like code in a code nugget. It is fully-formed code that must follow the rules of the current language; for example, each line of code written in C# must include a semicolon (;) at the end, just as if it lived within a class in a .cs file.

How Razor Parses Markup and Code

The @ symbol is the heart of the Razor syntax, the character that Razor uses to differentiate code from markup. The @ symbol marks a point at which the developer intends to switch from markup to code. In simple cases, no additional characters are needed to indicate when the code stops and the markup resumes. Razor’s intelligent parser determines which parts of the template are code and which are markup. What makes a valid code statement? Razor uses the following algorithm to find the end of a code statement once it reads the @ symbol trigger:

1. Read to the end of a valid identifier (i.e., a C# or VB keyword) or variable name.

2. If the next character is an opening bracket ( ( or [ )…

a. Keep parsing until the corresponding closing bracket is located. Nested brackets

are also tracked to avoid premature closing of a block.

b. Loop back to #2.

3. If the next character is a . (period) and precedes a valid identifier, jump to #1.

4. Complete the code statement and continue processing the rest of the markup.

Razor relies on the current language’s syntax to determine the end of a code statement. Razor also attempts to “read forward,” checking if the upcoming content resembles code or markup. The specifics depend on the language currently in use (C# or VB). Here’s a typical Razor snippet:

@foreach(var item in order.Items) {

<li>@item.Name</li>

}

The first line initializes the loop variables and opens the loop with an opening bracket;the second line renders markup; and the third line contains the closing bracket to end the loop. There is a clear transition between code and markup because the second line begins with an <li> tag that is clearly an HTML element and the third line is clearly the foreach loop’s closing tag.


The @: Character sequence  

The @: character sequence indicates a transition, telling Razor to assume that the content that follows the sequence is content, not code. You are still free to use the @ symbol any time after transitioning to content mode to execute code, just as in any other part of the Razor template. The following example shows the @: character sequence in action:

@if(User.IsAuthenticated) {
@:Hello, @User.Name!
}
else {
@:Please login
}

The conditional markup in this example does not specify any HTML, so it is difficult for Razor to figure out when or if to transition to markup mode. After all, how can Razor know whether “Hello” is a class name or an arbitrary word? The markup in the if condition uses the @: character sequence to specify that “Hello” is actually content and not code. The same markup then switches back to code mode to render the value of the User.Name property. The markup in the else condition also uses the @: character sequence to indicate that the text should be rendered verbatim.


How can you Comments your Code in Razor ?

Many developers strive to write code in such a way that the code documents itself. Sometimes, however, it’s not possible; perhaps there is a particularly complex bit of markup, or you need to leave a note for the next developer to come along (who might be you). Or you need to temporarily exclude a portion of a template without deleting it entirely. To support these scenarios, Razor lets you comment out portions of markup with the

@* *@ 

syntax. Any markup wrapped in a Razor comment block will remain in the template but will not have any effect on rendering. Here is a simple Razor template with a few parts commented out:

First
@* Second *@
Third @* Fourth *@ Fifth

This template renders the output:

First
Third Fifth

 

The Second and Fourth words are not included in the output, and are completely ignored by Razor. 


Conclusion 


This is the first article of this kind coming from me , in few days time i will continue on Razor , Thank you for visiting DotnetFunda. 

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:11 year(s)
Home page:http://www.Dotnetfunda.com
Member since:Sunday, July 06, 2008
Level:NotApplicable
Status: [Member] [MVP] [Administrator]
Biography:Vuyiswa Junius Maseko is a programmer and a moderator in ".NetFunda. Vuyiswa has been developing for 9 years now. his major strength are C# 1.1,2.0,3.0,3.5 and sql and his interest are in Silverlight,WPF,C#,Kinect , Xbox Gaming Dev.
 Responses
Posted by: Sandy's | Posted on: 29 Aug 2012 02:59:16 AM | Points: 25

nice to learn basic on razor dude. i am working on this...;)

>> Write Response - Respond to this post and get points
Related Posts

In this article, we are going to learn How to play audio in the HTML5 and how to control the audio play using in HTML element.

In this article you will learn HTML5 new descriptive elements.

In this article, we are going to learn new form elements introduced in HTML5.

This article gives some brief introduction on Canvas element in HTML 5 that can exposes the fundas of how the canvas element works with an example.

HTML 5 has a very nice drawing API in the form of new Canvas element. Canvas is used for rendering graphs, game graphics, or other visual images on the fly. Canvas is a rectangular area that we can add to our HTML5 page. In this article, we shall learn how to draw a shape on the HTML 5 Canvas and save it as image on the server.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/24/2013 7:40:22 PM