Back to: ASP.NET Core Tutorials For Beginners and Professionals
Razor View Engine and Razor Syntax in ASP.NET Core
In this article, I am going to discuss Razor View Engine and Razor Syntax in ASP.NET Core MVC Web Application with Examples. Please read our previous article discussing View Components in ASP.NET Core MVC. At the end of this article, you will understand the following pointers.
- What is View Engine?
- What is Razor View Engine?
- How Does the Razor View Engine Work?
- What is Razor Markup?
- Multiple Examples to Understand Razor Markup Syntax in ASP.NET Core MVC
What is View Engine?
A view engine is a web application framework component responsible for rendering a web page’s user interface (UI) or presentation layer. It takes data from the server and combines it with templates or markup to generate the final HTML that is sent to the client’s browser. View engines play a crucial role in separating the presentation logic from the application’s business logic, promoting clean code architecture and maintainability.
In the context of web frameworks like ASP.NET Core MVC, view engines are used to dynamically generate HTML based on the application’s data and logic. One of the popular view engines used in ASP.NET Core MVC is the Razor view engine. Razor allows developers to embed C# code directly within HTML markup, making it easy to generate dynamic content. Here’s how a typical view engine like Razor works:
- Template Creation: Developers create template files that contain a mixture of markup (HTML) and embedded code (e.g., C# in the case of Razor). These templates define how the final HTML should be structured and what data should be included.
- Data Binding: The controller in a web framework retrieves data from various sources (e.g., databases, APIs, services) and prepares it to be sent to the view.
- Rendering: When a user requests a particular page, the framework’s routing mechanism maps the request to an appropriate controller action. The controller action retrieves the necessary data and passes it along with the appropriate template to the view engine.
- Merging Data and Template: The view engine processes the template, combining the embedded code with the provided data. It generates the final HTML output that represents the web page.
- Response to Client: The generated HTML is then sent as the HTTP response to the client’s browser, where it is rendered and displayed as the user interface.
View engines provide several benefits:
- Separation of Concerns: View engines help separate the presentation layer from the application’s core logic, adhering to clean architecture and maintainability principles.
- Code Reusability: View templates can be reused across different parts of the application or even in different applications.
- Dynamic Content Generation: View engines allow developers to create dynamic web pages that can display different content based on user input, data from databases, or other sources.
- Consistent UI: View engines make maintaining a consistent user interface design easier across the application.
- Testability: Separating the view logic from the business logic makes it easier to write unit tests for different parts of the application.
What is Razor View Engine?
The Razor view engine is a markup syntax and rendering engine that is used in various Microsoft web development frameworks, including ASP.NET Core MVC. It provides a compact, expressive, and efficient way to generate dynamic HTML content by combining server-side code (typically written in C#) with HTML markup.
Razor was introduced to address some of the challenges and limitations of traditional view engines by providing developers with a more natural and fluid syntax. It aims to make the creation of dynamic web pages more intuitive and maintainable.
Key features and concepts of the Razor view engine include:
- Compact Syntax: Razor uses a concise and readable syntax that allows you to embed C# code within HTML markup seamlessly. This helps reduce the need for explicit code blocks and provides a more fluid development experience.
- Code Blocks: You can use code blocks within Razor views by enclosing C# code in @{ … } blocks. This allows you to perform operations, logic, and data manipulation directly within the view.
- Expression Syntax: Razor uses the @ symbol to indicate that you’re entering C# code within HTML. For example, @Model.Property is used to output the value of a property from the model.
- Helpers: Razor includes built-in helper methods that simplify common tasks, such as rendering partial views, generating URLs, and rendering HTML elements with attributes.
- Layouts: Razor supports the concept of layouts, which define the overall structure of a page and provide a consistent template for your views. Layouts help separate the common UI elements from the specific content of individual pages.
- Partial Views: Razor allows you to create partial views, which are reusable components that can be included in other views. This promotes code reusability and modularity.
- Model Binding: Razor supports model binding, which allows you to bind data from your model classes to the view’s markup, making it easy to display and interact with data.
- IntelliSense and Syntax Highlighting: Most integrated development environments (IDEs) provide robust support for Razor syntax highlighting, code completion, and IntelliSense, which enhance the development process.
The Razor view engine has become popular for developers working with ASP.NET Core MVC due to its intuitive syntax and powerful features for creating dynamic web content. It helps developers build maintainable and efficient web applications by promoting the separation of concerns and clean code architecture.
How Does the Razor View Engine Work?
The Razor view engine processes Razor markup within views (HTML templates) to generate dynamic HTML content sent to the client’s web browser. It allows developers to embed C# code directly into HTML, enabling the creation of dynamic and data-driven web pages. Here’s how the Razor view engine works step by step:
View Creation and Markup:
- Developers create views using Razor syntax. These views contain a mix of HTML markup and embedded C# code.
- Views may also include placeholders for dynamic data from the model or other sources.
Client Request and Controller Action:
- When a user makes a request for a specific URL, the ASP.NET Core MVC framework’s routing system maps the request to a specific controller action.
- The controller action retrieves any necessary data from databases, services, or other sources.
Rendering Process:
- The controller action selects the appropriate view and passes the data (the model) to it.
- The Razor view engine processes the view, combining the HTML markup with the embedded C# code.
C# Code Execution:
- The Razor view engine executes the embedded C# code in the view. This code can include logic, loops, conditionals, variable assignments, and function calls.
HTML Generation:
- As the Razor engine processes the view, it generates dynamic HTML content by evaluating the embedded C# code and producing corresponding HTML elements.
- Data from the model is inserted into the HTML at the appropriate locations.
Layout Application (Optional):
- If a layout is specified for the view, the Razor view engine applies the layout’s structure around the generated HTML content. Layouts allow you to define a consistent structure for your pages (e.g., headers, footers, navigation) while leaving the content area flexible.
Final HTML Output:
- The Razor view engine generates the final HTML output, including the processed C# code, dynamic data, and layout structure.
Response to Client:
- The generated HTML content is sent to the client’s web browser as the HTTP response.
Client Rendering:
- The client’s browser receives the HTML response and renders the page, displaying the dynamic content and UI elements.
- The browser also processes any JavaScript or CSS included in the view.
Throughout this process, the Razor view engine manages the seamless integration of C# code and HTML markup, resulting in a dynamic and interactive user interface. This approach helps developers maintain clean code separation, allowing them to focus on building a responsive and feature-rich web application without compromising maintainability.
It’s important to note that while this explanation provides a high-level overview of how the Razor view engine works, the specific implementation details, and optimizations may vary based on the framework and version being used.
What is Razor Markup?
Razor Markup refers to the syntax used in Razor view templates in ASP.NET web applications to combine server-side code with HTML markup. Razor Markup allows developers to embed C# code directly within HTML, making generating dynamic and data-driven content for web pages easier. The Razor Markup syntax is designed to be concise, readable, and intuitive, enabling seamless integration of code and markup.
The Controller in ASP.NET Core MVC invokes the View by passing the data to render. The Views must have the ability to process the data and generate a response. This is done using the Razor markup, which allows us to use C# code in an HTML file. The Razor View Engine process these markups to generate the HTML.
The files containing Razor markup generally have a .cshtml file extension. The Razor syntax is shorter, simpler, and easy to learn as it uses the C# or visual basic. The Visual Studio IntelliSense support also helps with Razor syntax.
Example to Understand Razor Syntax in ASP.NET Core MVC:
First, create a new ASP.NET Core Web Application using the Model-View-Controller Project template with the name RazorSyntaxDemo. Then create a class file with the name Product.cs within the Models folder and then copy and paste the following code.
namespace RazorSyntaxDemo.Models { public class Product { public long ProductID { get; set; } public string? Name { get; set; } = null!; public string Category { get; set; } = null!; public string Description { get; set; } = null!; public decimal Price { get; set; } } }
Razor Syntax in ASP.NET Core MVC:
The Razor uses the @ symbol to switch from HTML markup to the C# code. The following are the two ways by which you can achieve the transitions.
- Using Razor code expressions
- Using Razor code blocks.
These expressions are evaluated by the Razor View Engine and written to the response.
Razor Code Block Syntax in ASP.NET Core MVC:
The Razor code blocks start with @ symbol followed by curly braces. You can use code blocks anywhere in the markup. A Razor code block can be used to manipulate a model, declare variables, set local properties on a view, etc. However, it would be best if you did not use it for business logic.
Now, open the index.cshtml file of Home Controller and copy and paste the following code into it.
<h3>Code Block</h3> @{ var greeting = "Welcome to ASP.NET Core MVC!"; var weekDay = DateTime.Now.DayOfWeek; ViewData["Title"] = "Home Page"; } @{ var product = new RazorSyntaxDemo.Models.Product() { ProductID = 1000, Name = "Laptop", Description= "Its a Gaming Laptop", Category = "Electronics", Price = 10000 }; }
First, we have created a Razor code block beginning with a @ symbol and { } curly brackets. Inside the Curly brackets, we have regular C# code, which declares greeting and weekDay Variables as well as a ViewData to hold the Title property. The Second Razor Code block creates a product variable, which is a new instance of the Product model class.
Razor Code Expression Syntax in ASP.NET Core MVC
The Razor Code expressions start with @ and are followed by C# code. The Code expression can be either Implicit or Explicit.
Implicit Razor Expressions
Implicit Razor expressions start with @ followed by C# code. In the below example, the codes @greeting, @DateTime.Now, and @WeekDay are treated as Implicit Razor expressions. Space is not allowed in the Code expression, as it is used to identify the end of the expression. The Razor View engine evaluates the expressions, and the result is inserted in their place.
<h3>Code Block</h3> @{ var greeting = "Welcome to ASP.NET Core MVC!"; var weekDay = DateTime.Now.DayOfWeek; ViewData["Title"] = "Home Page"; } @{ var product = new RazorSyntaxDemo.Models.Product() { ProductID = 1000, Name = "Laptop", Description= "Its a Gaming Laptop", Category = "Electronics", Price = 10000 }; } <h3>Code Expression</h3> <p>@greeting</p> <p>@DateTime.Now</p> <p>Today is : @weekDay thank you </p> <p>Name : @product.Name</p> <p>Description : @product.Description</p> <p>Price : @product.Price</p>
Now, run the application, and you should see the following output.
Explicit Razor Expressions
Explicit Razor expressions start with @ followed by (). Any content within the () parenthesis is evaluated and rendered to the output.
<h3>Code Block</h3> @{ var greeting = "Welcome to ASP.NET Core MVC!"; var weekDay = DateTime.Now.DayOfWeek; ViewData["Title"] = "Home Page"; } @{ var product = new RazorSyntaxDemo.Models.Product() { ProductID = 1000, Name = "Laptop", Description= "Its a Gaming Laptop", Category = "Electronics", Price = 10000 }; } <h3>Code Expression</h3> <p>@(greeting)</p> <p>@(DateTime.Now)</p> <p>Today is : @(weekDay) thank you </p> <p>Name : @(product.Name)</p> <p>Description : @(product.Description)</p> <p>Price : @(product.Price)</p>
Now, run the application, and you should see the following output.
IntelliSense Support in Razor Syntax
The image below shows how the Razor markup is used inside an HTML page and the Intelligence support from Visual Studio.
Using Directive
The @using directive works similarly to the C# using directive and allows you to import namespaces and the RazorSyntaxDemo.Models can be imported as shown below. Here, you don’t need to need the statement with a semicolon.
@using RazorSyntaxDemo.Models
And then, we can use var product = new Product() instead of var product = new RazorSyntaxDemo.Models.Product() as follows:
@using RazorSyntaxDemo.Models <h3>Code Block</h3> @{ var greeting = "Welcome to ASP.NET Core MVC!"; var weekDay = DateTime.Now.DayOfWeek; ViewData["Title"] = "Home Page"; } @{ var product = new Product() { ProductID = 1000, Name = "Laptop", Description= "Its a Gaming Laptop", Category = "Electronics", Price = 10000 }; }
Variable Declaration using Razor Syntax in ASP.NET Core MVC
The Variables are declared using the var keyword or using the C# data type. The int, float, decimal, bool, DateTime & string keywords can be used to store strings, numbers, dates, etc. The variables are inserted directly into a page using @.
<h3>Variables </h3> <!-- Storing a string --> @{ string message = "Welcome to ASP.NET Core MVC"; } <!—Storing date and integer--> @{ DateTime date = DateTime.Now; int Number = 100; } <p>@message</p> <p> The current date is @date</p> <p>Numbers : @Number</p>
Now, run the application, and you should see the following output.
Strings are enclosed in double quotation marks. To use a double quotation mark inside the string, use a verbatim string literal. The verbatim string is prefixed with the @ symbol and repeats the quotation mark.
@{ var helloWorld = @"Hello ""World"""; } <p>@helloWorld</p>
Similarly, backslash characters can be printed using the same technique.
@{ var Path = @"C:\Windows\"; } <p>The path is: @Path</p>
You can print @ in HTML by repeating (Escape) the @ symbol as shown below.
@{ var symbol = "You can print @ in html"; } <p>The @@symbol is: @symbol</p>
So, modify the Index view as follows:
@{ var helloWorld = @"Hello ""World"""; } <p>@helloWorld</p> @{ var Path = @"C:\Windows\"; } <p>The path is: @Path</p> @{ var symbol = "You can print @ in html"; } <p>The @@symbol is: @symbol</p>
Now, run the application, and you should see the following output.
Comments
Use @* *@ to place comments
@*This is comment*@
HTML Elements inside the code block
The Razor Engine Correctly Identifies any HTML Elements inside the Razor code block, as shown below.
@{ <p>Hello from the Code block</p> }
Single line text
You can output the literal values without the HTML element by prefixing it with @: and @: used to define the single line of literal values.
@{ @:Hello from the Code block }
Multiline text
For the multiline text use the <text> </text> element
@{ <text> Multiline text 1 Multiline text 2 Multiline text 3 </text> }
Conditional Statements
The Razor engine is able to process conditional statements like if and Switch statements.
If and Else Conditions
If Condition is used to render a section based on a condition as shown below.
@{ int value = 200; } @if (value > 100) { <p>Value is greater than 100</p> } else { <p>Value is less than 100</p> }
Or you can use the following code.
@{ var value = 200; if (value > 100) { <p>The value is greater than 100</p> } else { <p>This value is less than 100</p> } }
Switch Statements in Razor View
A switch statement can insert a section into HTML based on a number of conditions.
@{ var value = 200; } @switch (value) { case 0: @: value is Zero break; case 100: <p>Value is 100 </p> break; case 200: <p>Value is @value </p> break; case 300: <text>Value is 300</text> break; default: <p>Invalid Value </p> break; }
Loops
For loop
The loops are used to repeat a code block for,
@for (int i = 0; i < 5; i++) { <span> @i </span> }
Foreach loop
The best use case of a for-each loop is to loop through a collection object and display the result inside a table.
@using RazorSyntaxDemo.Models @{ var productList = new List<Product>() { new Product() { ProductID = 1001, Name = "Laptop", Price = 1000 }, new Product() { ProductID = 1002, Name = "Desktop", Price = 2000 }, new Product() { ProductID = 1002, Name = "Mobile", Price = 3000 } }; } <table> <thead> <tr><td>ProductID</td><td>Name</td><td>Price</td></tr> </thead> @foreach (Product product in productList) { <tr> <td>@product.ProductID</td> <td>@product.Name</td> <td>@product.Price</td> </tr> } </table>
While loop:
<h3>While loop</h3> @{ var r = 0; while (r < 5) { r += 1; <span> @r</span> } }
In the next article, I am going to discuss How to Install Bootstrap in ASP.NET Core MVC Application. Here, in this article, I try to explain Razor View Engine and Razor Syntax in ASP.NET Core MVC Application. I hope you enjoy this Razor View Engine and Razor Syntax in ASP.NET Core MVC article.