Introduction of Razor View Engine in ASP.NET MVC
ASP.NET MVC 3 introduces a new view engine named
Razor that offers the following
syntax is clean and concise, requiring a minimum number of keystrokes.
easy to learn, in part because it's based on existing languages like C# and
Studio includes IntelliSense and code colorization for Razor syntax.
Some new Razor features include the following:
@model syntax for specifying the type being
passed to the view.
@* *@ comment syntax.
ability to specify defaults (such as
layoutpage) once for an entire site.
Html.Raw method for displaying text without
for sharing code among multiple views (_viewstart.cshtml
Razor also includes new HTML helpers, such as the following:
Chart: Renders a chart, offering the same
features as the chart control in ASP.NET4.
WebGrid: Renders a data grid, complete with
paging and sorting functionality.
Crypto: Uses hashing algorithms to create
properly salted and hashed passwords.
WebImage: Renders an image.
WebMail: Sends an email message.
Let’s we create our first MVC Application by using Razor View syntax:
à Select ASP.NET MVC 3 Web Application
à Click OK.
Razor View engine from the DropDownList for your application and Click OK.
application is ready add a view in your project and select
Razor as a View engine. Add it in your project.
have created two properties ((name,
productid) in a Model class that
return the name of an individual and productid respectively.
Here in a
HomeController class I have created
two action methods Index() and
Product() that return an Index and
Product View respectively.
if (id == 1)
products = new List<string>();
the start of a code block with Razor using a
@ character. Unlike <% %> code
nuggets, Razor does not require you to explicitly close the code-block:
Today is @DateTime.Now.DayOfWeek
below code we started a “foreach”
loop using the @ symbol, and then
contained a line of HTML content with code blocks within it. Because the
Razor parser understands the C# semantics in our code block, it was able to
determine that the <li> content
should be contained within the foreach and treated like content that should be
looped. It also recognized that the trailing} terminated the foreach
product in ViewBag.Products)
the browser we can see the output of our application:
When we click on hyperlink it will displays the product below:
By using the above code example you can easily learn how to use razor view
syntax in a MVC Application.