Razor in .NET
Beginner’s Guide to Razor in .NET
What is Razor?
Razor is a lightweight, syntax-based view engine for creating dynamic web pages in ASP.NET. It is designed to combine server-side code with HTML in a clean and straightforward way. Razor is a part of the ASP.NET Core framework and is commonly used in applications built with ASP.NET MVC or Razor Pages.
Why Do We Need Razor?
- Seamless Integration: Razor allows embedding C# code directly within HTML.
- Simple Syntax: It offers a concise and intuitive syntax, making it easier to write and maintain.
- Efficiency: Razor eliminates the need for switching between multiple languages or files, reducing development time.
- Flexibility: It supports rich features like loops, conditions, and functions.
- Security: Razor prevents cross-site scripting (XSS) by default when rendering user input.
Razor Syntax
Razor syntax is primarily built around the @
symbol, which indicates the start of server-side code. Below is a breakdown of key Razor syntax features:
1. Inline C# Code
<p>The current year is @DateTime.Now.Year</p>
- This outputs the current year dynamically by embedding C# code.
2. Code Blocks
@{ var name = "Areen"; var age = 17;}<p>Hello, my name is @name and I am @age years old.</p>
- Code blocks allow you to define variables and logic that can be used within the HTML.
3. Loops
<ul> @for (int i = 1; i <= 5; i++) { <li>Item @i</li> }</ul>
- Razor supports loops like
for
,foreach
,while
, etc., for iterating over collections or performing repetitive tasks.
4. Conditional Statements
@{ var isLoggedIn = true;}@if (isLoggedIn){ <p>Welcome back!</p>}else{ <p>Please log in.</p>}
- Use
if
,else
, and other conditional statements to control the flow of your application.
5. Rendering HTML Safely
@{ var unsafeHtml = "<script>alert('Hack!')</script>";}<p>@Html.Raw(unsafeHtml)</p>
- Razor escapes potentially harmful HTML by default. Use
Html.Raw
cautiously to render raw HTML.
6. Using Models in Razor Pages
@model MyApp.Models.User<p>Welcome, @Model.Name!</p>
- Razor pages can bind directly to a model class, making it easier to work with data.
7. Partial Views
@Html.Partial("_Header")
- Partial views allow you to break your UI into reusable components.
8. Comments
@* This is a Razor comment. It won't appear in the rendered HTML *@<!-- This is an HTML comment. It will appear in the rendered HTML -->
Getting Started with Razor Pages
- Create a New Razor Pages Project:
- Run the following command in your terminal:
Terminal window dotnet new webapp -o RazorTutorial
- Run the following command in your terminal:
- Structure of a Razor Page:
- A Razor page consists of two main files:
.cshtml
: Contains the HTML and Razor syntax..cshtml.cs
: Contains the page’s backend logic.
- A Razor page consists of two main files:
- Running the Application:
- Navigate to the project directory and run:
Terminal window dotnet run
- Navigate to the project directory and run:
Razor Syntax Table
Syntax Feature | Code Example | Description |
---|---|---|
Inline C# Code | <p>The year is @DateTime.Now.Year</p> | Embeds C# expressions in HTML. |
Code Blocks | @{ var name = "Areen"; } | Allows defining variables and logic within a block. |
Loops | @for (int i = 1; i <= 5; i++) { <li>Item @i</li> } | Supports looping structures like for , foreach , etc. |
Conditional Statements | @if (isLoggedIn) { <p>Welcome!</p> } else { <p>Please log in.</p> } | Implements conditional logic in Razor views. |
Using Models | @model MyApp.Models.User <p>@Model.Name</p> | Binds a Razor page to a specific model class. |
Partial Views | @Html.Partial("_Header") | Renders a reusable partial view. |
Comments | @* Razor comment *@ <!-- HTML comment --> | Adds comments in Razor or HTML. |
Rendering Raw HTML | @Html.Raw("<b>Bold Text</b>") | Renders raw HTML without escaping it. |
Conclusion
Razor is a powerful and easy-to-learn view engine that simplifies the process of building dynamic web applications in .NET. By mastering the Razor syntax and understanding its integration with HTML and backend logic, you can create robust and scalable web applications efficiently.