In this razor tutorial you learn how to write razor syntax in view in asp.net nvc application.
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
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, 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> } }
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 @Html.Partial("_securePartialView") <div> this is plain Html for authorised user</div> } else { // display common partial view @Html.Partial("_commonPartialView") <div> this is plain Html for common user</div> }
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 Asp.net MVC without model data.
@Html.DropDownList("countryList", objListItems, "Select Country")
Razor syntax for binding model data with dropdownlist in Asp.net MVC
@Html.DropDownListFor(model => model.Country, objListItems, "Select Country")
You may like to know more about Partial View in Razor in Asp.net MVC