Online Training for MVC Web Designing Development, MS SQL, Digital Marketing

Razor in MVC, MVC Tutorial

What is Razor in MVC?

Razor is view engine in ASP.NET MVC. Razor allows you to write mix of HTML and server side code using C# or Visual Basic (Yes, earlier how we used to write in classic asp! But wait, razor has much more). Razor view with visual basic syntax has .vbhtml file extension and C# syntax has .cshtml file extension.

Here are important things about Razor
  • Intellisense: Razor syntax supports statement completion within Visual Studio.
  • Esay to Differentiate: Easily you can differentiate server side code from html code
  • Inline expression: in Razor it's much easier to write inline expression

How to write Razor Syntax in MVC?

In Razor syntax server side code written inside @{} and single line server side code start with @
Now let's look at some example
var message = "I am learning Razor today";

<h1>@message @DateTime.Now.ToShortDateString() </h1>

You can easily mix-up server side code with html, server side code reside within @{ } bracket, look at the below example
Here i am printing number 1 to 10 using loop, this is my plain html message
for(int i=1;i<=10;i++)
<div>Current number : @i</div>

Suppose you want to write server side if else statement, and based condition display different user interface to end user
// get this value dynamically from database.
bool allowUser = true;
@if (allowUser)
// display secured partial view
<div> this is plain Html for authorised user</div>
// display common partial view
<div> this is plain Html for common user</div>

You may like to know more about Partial View in Razor in MVC

Learn Razor Syntax in MVC

Group Training