Introduction to Razor:
Razor is a markup syntax that lets us embed server-based code (Visual Basic and C#) into web
pages. Server-based code can create dynamic web content on the fly, while a web page is
written to the browser. When a web page is called, the server executes the server-based code
inside the page before it returns the page to the browser. By running on the server, the code
can perform complex tasks, like accessing databases. Razor is based on ASP.NET, and
designed for creating web applications. It has the power of traditional ASP.NET markup, but it is
easier to use, and easier to learn.
Razor Syntax:
Razor uses a syntax very similar to Classic ASP.
<ul>
@for (int i = 0; i < 10; i++)
{
<li>@i</li>
}
</ul>
Razor Helpers
ASP.NET helpers are components that can be accessed by single lines of Razor code. We can
build our own helpers using Razor syntax, or use built-in ASP.NET helpers. Below is a short
description of some useful Razor helpers:
Web Grid
Web Graphics
Google Analytics
Facebook Integration
Twitter Integration
Sending Email
Validation
Main Razor Syntax Rules for C#
Razor code blocks are enclosed in @{ ... }
Inline expressions (variables and functions) start with @
Code statements end with semicolon
Variables are declared with the var keyword
Strings are enclosed with quotation marks
C# code is case sensitive
C# files have the extension .cshtml
For example:
@{ var myMessage = "Hello World"; }
<!-- Inline expression or variable -->
<p>The value of myMessage is: @myMessage</p>
<!-- Multi-statement block -->
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Here in Huston it is: " + weekDay;
}
<p>The greeting is: @greetingMessage</p>
How it works:
Razor is a simple programming syntax for embedding server code in web pages.
Razor web pages can be described as HTML pages with two kinds of content: HTML content
and Razor code.
When the server reads the page, it runs the Razor code first, before it sends the HTML page to
the browser. The code that is executed on the server can perform tasks that cannot be done in
the browser, for example accessing a server database. Server code can create dynamic HTML
content on the fly, before it is sent to the browser. Seen from the browser, the HTML generated
by server code is no different than static HTML content.