Razor View Engine

Level : Beginner
Mentor: Shailendra Chauhan
Duration : 00:02:00

Razor View Engine

The Razor View Engine is a key component of ASP.NET Core for creating dynamic web pages with a combination of HTML and C# or Visual Basic code. It provides a clean and efficient way to generate dynamic content within views by using a concise and expressive syntax.

Example

@{
  string message = "Hello, Razor!";
}
<p>@message</p>

Razor Markup

Razor Markup is the foundation of the Razor View Engine, allowing developers to seamlessly integrate C# or Visual Basic code into HTML templates. It simplifies the process of rendering dynamic content by using a minimalistic, readable syntax.

Example

<p>Welcome to Razor Markup!</p>

Razor Syntax in MVC

Razor Syntax in MVC refers to the specific set of rules and conventions used to embed C# or Visual Basic code into views, making it easier to build dynamic web applications with the Model-View-Controller (MVC) architecture.

Example

@model MyModel
<p>Name: @Model.Name</p>
<p>Age: @Model.Age</p>

Single Block Statements

Razor allows you to execute single C# or VB statements within your views, enabling dynamic content generation in a concise manner.

Example

@{
  int count = 5;
}
<p>There are @count items in the list.</p>

Multi-Statement Block

You can use multi-statement blocks in Razor to include multiple lines of code for more complex logic within your views.

Example

@{
  int x = 10;
  int y = 20;
  int sum = x + y;
}
<p>The sum of @x and @y is @sum.</p>

Variables

Razor allows you to declare and use variables within your views, making it easy to store and display data dynamically.

Example

@{
  string productName = "ASP.NET Core";
}
<p>Product Name: @productName</p>

Conditions

Razor supports conditional statements like if-else, enabling you to create dynamic content based on certain conditions.

Example

@if (UserIsAuthenticated)
{
  <p>Welcome, authenticated user!</p>
}
else
{
  <p>Please log in to access this content.</p>
}

Loops

You can use loops in Razor to iterate through collections or generate repetitive HTML elements dynamically.

Example

<ul>
  @foreach (var item in itemList)
  {
    <li>@item.Name</li>
  }
</ul>

Model

In MVC, the model represents the data and business logic of an application. Razor allows you to work with models to display and manipulate data within views.

Example

@model User
<p>User Name: @Model.UserName</p>
<p>Email: @Model.Email</p>
Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this