Free Web Development Online Tutorials, Learn to Code
Learn MVC C#, MVC Tutorial for Beginners, Model View Controller

Razor Syntax in MVC C# Example

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

foreach razor syntax

Here i am printing number 1 to 10 using loop, this is my plain html message, you can see how to mix html code with razor syntax.

@{ for(int i=1;i<=10;i++)
        <div>Current number : @i </div>

You also can print any server side object value, jsut think of situation where you have a student list, and you want to display student name and mobile number on razor view.

List<Student> stuList=CFD.GetStdentList();       
    foreach(Student s in stuList)
        <div> @s.FullName @s.MobileNumber  </div>
if else razor syntax

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>

MVC Razor Syntax for DropDownList

Here are some examples of how you can bind dropdownlist in mvc razor syntax

First we need to create a SelectListItem collection object

   List<SelectListItem> objListItems= new List<SelectListItem>();
   listItems.Add(new SelectListItem
        {Text = "India", Value = "1",Selected = true});
   listItems.Add(new SelectListItem
        {Text = "USA",Value = "2"});
   listItems.Add(new SelectListItem
        {Text = "Canada", Value = "3"});

Razor syntax for dropdownlist in MVC without model data.

@Html.DropDownList("countryList", objListItems, "Select Country")

Razor syntax for binding model data with dropdownlist in MVC

@Html.DropDownListFor(model => model.Country, objListItems, "Select Country")

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