Module 2: Deep Dive into MVC Components
2.2.1. Introduction to Razor View Engine
Overview
In the Model-View-Controller (MVC) architectural pattern, the View component is responsible for presenting data to the user. To effectively create dynamic and interactive web pages, the view engine is a crucial tool that facilitates the seamless integration of server-side code with client-side markup. In ASP.NET MVC, the Razor View Engine stands out as a powerful and efficient engine for rendering views.
This section delves deeply into the Razor View Engine, exploring its definition, core functionalities, syntax, and practical usage through comprehensive code examples. By the end of this section, you'll have a thorough understanding of how Razor operates within the MVC framework, enabling you to build sophisticated and maintainable web applications.
Table of Contents
- What is Razor?
- Combining C# Code with HTML
- Razor Syntax Basics
- Using C# in Views
- Advanced Razor Features
- Best Practices and Common Pitfalls
- Comprehensive Code Examples
- Summary
What is Razor?
Razor is a markup syntax for embedding server-based code into web pages, primarily used within the ASP.NET MVC framework. Introduced by Microsoft, Razor allows developers to seamlessly integrate C# or VB.NET code into HTML, facilitating the creation of dynamic web content.
Key Features of Razor:
-
Lightweight Syntax: Razor's syntax is concise, reducing the verbosity often associated with other templating engines. It minimizes the amount of code you need to write, leading to cleaner and more maintainable views.
-
Seamless Integration: Razor is tightly integrated with ASP.NET MVC, ensuring that server-side code and client-side markup work harmoniously.
-
IntelliSense Support: In development environments like Visual Studio, Razor benefits from IntelliSense, providing auto-completion and real-time error checking as you code.
-
Automatic HTML Encoding: To protect against cross-site scripting (XSS) attacks, Razor automatically encodes content, ensuring that dynamically injected data doesn't pose security risks.
Razor vs. Other View Engines:
Before Razor, ASP.NET MVC primarily used Web Forms as the view engine. However, Razor offers several advantages over Web Forms:
-
Cleaner Syntax: Razor's syntax is less cluttered, making the views easier to read and write.
-
Performance: Razor views tend to be faster due to their lightweight nature.
-
Separation of Concerns: Razor promotes a clear separation between server-side logic and HTML, adhering to MVC principles.
Combining C# Code with HTML
One of Razor's primary strengths is its ability to intertwine server-side C# code with client-side HTML markup seamlessly. This integration allows developers to create dynamic and responsive web pages that react to user input, data from databases, and other runtime factors.
Example:
Consider a simple scenario where you want to display a personalized greeting based on the time of day. Using Razor, you can embed C# logic directly within your HTML.
@{
var currentHour = DateTime.Now.Hour;
string greeting;
if (currentHour < 12)
{
greeting = "Good morning";
}
else if (currentHour < 18)
{
greeting = "Good afternoon";
}
else
{
greeting = "Good evening";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Greeting Page</title>
</head>
<body>
<h1>@greeting, User!</h1>
</body>
</html>
Explanation:
-
Code Block (@{ }): The @{ } syntax denotes a Razor code block where you can write C# code.
-
C# Logic: Within the code block, you determine the current hour and set an appropriate greeting message.
-
Embedding Variables: The @greeting syntax injects the value of the greeting variable into the HTML content.
This example illustrates how Razor allows for the integration of logic and presentation within the same file, making it easier to create dynamic content without switching contexts between different languages or frameworks.
Razor Syntax Basics
Understanding Razor's syntax is fundamental to leveraging its full capabilities. Razor provides a set of syntax rules that dictate how server-side code interacts with HTML.
Razor Code Blocks (@{ })
Code blocks are sections of C# code embedded within the view. They allow you to execute logic, declare variables, and perform operations that impact the rendered HTML.
Syntax:
@{
// C# code here
var message = "Hello, Razor!";
}
Detailed Breakdown:
-
@{ }: The curly braces encapsulate a block of C# code.
-
Inside the Block: You can declare variables, execute loops, conditionals, and any other C# operations.
Use Cases:
- Defining variables that will be used later in the view.
- Performing calculations or data transformations.
- Executing control flow statements like loops and conditionals.
Example:
@{
var items = new List<string> { "Apple", "Banana", "Cherry" };
var count = items.Count;
}
<p>There are @count items in your list.</p>
Explanation:
-
A list of fruits is created, and the count of items is stored in the count variable.
-
The variable count is then embedded in the HTML paragraph, displaying the number of items.
Razor Expressions (@)
Expressions allow you to render the value of a C# expression directly into the HTML output. They are denoted by the @ symbol followed by the expression.
Syntax:
@expression
Detailed Breakdown:
Use Cases:
- Displaying variable values.
- Performing inline calculations.
- Invoking methods to retrieve data.
Example 1: Displaying a Variable
@{
var userName = "John Doe";
}
<p>Welcome, @userName!</p>
Explanation:
-
The userName variable is set to "John Doe".
-
The expression @userName injects this value into the paragraph, resulting in: "Welcome, John Doe!"
Example 2: Inline Calculation
<p>2 + 2 equals @ (2 + 2).</p>
Explanation:
- The expression
@ (2 + 2) calculates the sum and injects the result, displaying: "2 + 2 equals 4."
Operator Precedence:
- Razor intelligently determines when to treat
@ as an expression. However, parentheses can be used to clarify complex expressions and ensure correct evaluation.
Razor Comments (@* *@)
Comments in Razor are used to annotate the code without generating any output in the rendered HTML. They are especially useful for leaving notes or disabling sections of code during development.
Syntax:
@* This is a Razor comment *@
Detailed Breakdown:
Characteristics:
-
Server-Side: Razor comments are processed on the server and do not appear in the client-side HTML. This contrasts with HTML comments (<!-- -->), which are sent to the browser.
-
Nested Comments: Razor does not support nested comments. Attempting to nest Razor comments can lead to unexpected behavior.
Example Implementation:
@* This section displays the user greeting *@
@{
var greeting = "Hello, World!";
}
<p>@greeting</p>
Explanation:
-
The comment explains the purpose of the following code block.
-
Only "Hello, World!" is rendered in the HTML, and the comment remains only within the server-side code.
Best Practices:
-
Use Comments for Clarity: Utilize Razor comments to explain complex logic or to temporarily disable code without removing it.
-
Avoid Overuse: Excessive commenting can clutter the code. Strive for self-explanatory code where possible, using comments sparingly to clarify non-obvious sections.
Using C# in Views
Razor enables the embedding of C# code within views, allowing for dynamic content generation based on various conditions and data. This flexibility is vital for building responsive and interactive web pages.
Variables
Variables in Razor views allow you to store and manipulate data that can be used within the HTML markup. They can be declared within code blocks or as part of the model.
Declaring Variables in Code Blocks:
@{
string welcomeMessage = "Welcome to Razor!";
}
<p>@welcomeMessage</p>
Explanation:
-
Inside the @{ } block, a string variable welcomeMessage is declared and initialized.
-
The variable is then injected into the HTML using the @welcomeMessage expression, resulting in: "Welcome to Razor!"
Variable Scope:
-
Variables declared within a code block are accessible only within that block or subsequent code blocks within the same view.
-
To maintain clarity and prevent naming conflicts, limit the scope of variables and use descriptive names.
Data from the Model:
Razor views often receive data from a model. Accessing model properties is a common way to use dynamic data.
Example:
Assuming the view is strongly-typed with a model:
@model MyApp.Models.User
<p>Hello, @Model.FirstName @Model.LastName!</p>
Explanation:
-
@model directive specifies the type of the model being passed to the view.
-
@Model.FirstName and @Model.LastName access properties from the model, embedding them into the HTML.
Loops (@for, @foreach)
Loops enable iterative processing of collections, allowing you to render repeated elements based on data structures like arrays, lists, or database results.
@for Loop:
The @for loop is used for iterating a specific number of times or over a collection using an index.
Syntax:
@for (initialization; condition; iteration)
{
// Code to execute in each iteration
}
Example: Displaying a List of Numbers
@{
int totalNumbers = 5;
}
<ul>
@for (int i = 1; i <= totalNumbers; i++)
{
<li>Number @i</li>
}
</ul>
Output:
<ul>
<li>Number 1</li>
<li>Number 2</li>
<li>Number 3</li>
<li>Number 4</li>
<li>Number 5</li>
</ul>
Explanation:
-
The @for loop initializes i to 1, continues while i is less than or equal to totalNumbers, and increments i in each iteration.
-
For each iteration, a list item (<li>) is rendered, displaying the current value of i.
@foreach Loop:
The @foreach loop iterates over elements in a collection, providing direct access to each element without managing an index.
Syntax:
@foreach (var item in collection)
{
// Code to execute for each item
}
Example: Displaying a List of Fruits
@{
var fruits = new List<string> { "Apple", "Banana", "Cherry" };
}
<ul>
@foreach (var fruit in fruits)
{
<li>@fruit</li>
}
</ul>
Output:
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
Explanation:
-
The @foreach loop iterates over the fruits list, assigning each element to the fruit variable in each iteration.
-
A list item is rendered for each fruit, embedding the fruit name in the HTML.
Nested Loops:
Nested loops can be used to iterate over multi-dimensional collections or perform more complex iterations.
Example: Creating a Table of Products and Features
@{
var products = new List<Product>
{
new Product { Name = "Laptop", Features = new List<string> { "Touchscreen", "Backlit Keyboard" } },
new Product { Name = "Smartphone", Features = new List<string> { "Dual SIM", "Wireless Charging" } },
};
}
<table>
<thead>
<tr>
<th>Product</th>
<th>Features</th>
</tr>
</thead>
<tbody>
@foreach (var product in products)
{
<tr>
<td>@product.Name</td>
<td>
<ul>
@foreach (var feature in product.Features)
{
<li>@feature</li>
}
</ul>
</td>
</tr>
}
</tbody>
</table>
Explanation:
-
Outer @foreach: Iterates over each product in the products list.
-
Inner @foreach: For each product, iterates over its Features list, rendering each feature within a nested <ul>.
Rendered Output:
<table>
<thead>
<tr>
<th>Product</th>
<th>Features</th>
</tr>
</thead>
<tbody>
<tr>
<td>Laptop</td>
<td>
<ul>
<li>Touchscreen</li>
<li>Backlit Keyboard</li>
</ul>
</td>
</tr>
<tr>
<td>Smartphone</td>
<td>
<ul>
<li>Dual SIM</li>
<li>Wireless Charging</li>
</ul>
</td>
</tr>
</tbody>
</table>
Key Takeaways:
Conditionals (@if, @else)
Conditionals control the flow of content rendering based on specific conditions. They allow views to adapt content dynamically, showing or hiding elements based on data or user interactions.
@if Statement:
The @if statement evaluates a condition and executes the enclosed block if the condition is true.
Syntax:
@if (condition)
{
// Code to execute if condition is true
}
Example: Displaying a Message Based on User Login Status
@{
bool isLoggedIn = ViewBag.IsLoggedIn ?? false;
}
@if (isLoggedIn)
{
<p>Welcome back, @ViewBag.UserName!</p>
}
else
{
<p>Please <a href="/Login">log in</a> to continue.</p>
}
Explanation:
-
The isLoggedIn variable is retrieved from ViewBag.IsLoggedIn, defaulting to false if not set.
-
If isLoggedIn is true, a personalized welcome message is displayed.
-
Otherwise, a prompt to log in is shown.
@else if Statement:
For multiple conditions, @else if can be used to evaluate additional conditions if preceding ones fail.
Example: Displaying Different Greetings Based on Time of Day
@{
var currentHour = DateTime.Now.Hour;
}
@if (currentHour < 12)
{
<p>Good morning!</p>
}
else if (currentHour < 18)
{
<p>Good afternoon!</p>
}
else
{
<p>Good evening!</p>
}
Explanation:
-
The current hour is determined using DateTime.Now.Hour.
-
Based on the value of currentHour, the view displays an appropriate greeting.
@switch Statement:
For scenarios with multiple discrete conditions, a @switch statement can be more concise and readable.
Syntax:
@switch (expression)
{
case value1:
<p>Output for value1</p>
break;
case value2:
<p>Output for value2</p>
break;
default:
<p>Default output</p>
break;
}
Example: Displaying User Roles
@{
string userRole = ViewBag.UserRole ?? "Guest";
}
@switch (userRole)
{
case "Admin":
<p>Welcome, Administrator! You have full access.</p>
break;
case "Moderator":
<p>Welcome, Moderator! You can manage user content.</p>
break;
case "User":
<p>Welcome, User! Enjoy browsing our site.</p>
break;
default:
<p>Welcome, Guest! Please consider signing up.</p>
break;
}
Explanation:
-
The userRole variable is retrieved from ViewBag.UserRole, defaulting to "Guest" if not set.
-
The @switch statement evaluates userRole and renders different messages based on its value.
Nesting Conditionals and Loops:
Conditionals can be nested within loops and vice versa, allowing for complex rendering logic.
Example: Displaying Products with Stock Status
@{
var products = new List<Product>
{
new Product { Name = "Laptop", InStock = true },
new Product { Name = "Smartphone", InStock = false },
new Product { Name = "Tablet", InStock = true },
};
}
<ul>
@foreach (var product in products)
{
<li>
@product.Name -
@if (product.InStock)
{
<span style="color: green;">In Stock</span>
}
else
{
<span style="color: red;">Out of Stock</span>
}
</li>
}
</ul>
Explanation:
-
The @foreach loop iterates over each product in the products list.
-
For each product, an @if statement checks the InStock property and renders a status message with conditional styling.
Rendered Output:
<ul>
<li>Laptop - <span style="color: green;">In Stock</span></li>
<li>Smartphone - <span style="color: red;">Out of Stock</span></li>
<li>Tablet - <span style="color: green;">In Stock</span></li>
</ul>
Best Practices for Conditionals and Loops:
-
Maintain Readability: Keep the nesting levels shallow to prevent the view from becoming cluttered. If complex logic is required, consider moving it to the controller or using view models.
-
Use Indentation: Properly indent your Razor code to enhance readability and maintainability.
-
Limit Logic in Views: Avoid placing business logic in views. Use views primarily for presentation, delegating complex operations to controllers or services.
Advanced Razor Features
While the basics of Razor syntax cover most scenarios, there are advanced features that provide more flexibility and power when building views.
Razor Directives
Razor directives are instructions for the Razor engine, influencing how the view is processed. They typically begin with the @ symbol followed by a keyword.
Common Directives:
-
@model Directive:
Specifies the type of the model being passed to the view, enabling strong typing.
Syntax:
@model Namespace.To.YourModel
Example:
@model MyApp.Models.Product
<h1>@Model.Name</h1>
<p>Price: @Model.Price</p>
-
@using Directive:
Imports namespaces, allowing you to use classes without fully qualifying their names.
Syntax:
@using Namespace.To.Import
Example:
@using System.Text
@{
var builder = new StringBuilder();
builder.Append("Hello, ");
builder.Append("Razor!");
var message = builder.ToString();
}
<p>@message</p>
-
@inherits Directive:
Specifies the base class for the view.
Syntax:
@inherits Namespace.To.BaseClass
Example:
@inherits MyApp.Views.BaseView
<p>This view inherits from BaseView.</p>
-
@section Directive:
Defines a named section that can be rendered in a layout.
Syntax:
@section SectionName {
<!-- Content for the section -->
}
Example:
@section Scripts {
<script src="~/js/custom.js"></script>
}
Inline Functions
Razor allows the definition of inline functions within the view, enabling the reuse of code snippets without cluttering the view.
Syntax:
@functions {
public string GetGreeting(string name)
{
return $"Hello, {name}!";
}
}
Example:
@{
var userName = "Alice";
}
@functions {
public string GetGreeting(string name)
{
return $"Hello, {name}!";
}
}
<p>@GetGreeting(userName)</p>
Output:
<p>Hello, Alice!</p>
Explanation:
Note: While inline functions provide flexibility, it's advisable to keep business logic within the controller or service layers, using views primarily for presentation.
Best Practices and Common Pitfalls
Best Practices
-
Keep Logic Minimal in Views:
-
Views should primarily handle presentation. Complex business logic should reside in controllers or service layers.
-
Use view models to shape the data passed to views, ensuring views receive exactly what's needed for rendering.
-
Use Strongly-Typed Views:
-
Leverage the @model directive to create strongly-typed views, enabling IntelliSense and compile-time checking.
-
Strongly-typed views enhance maintainability and reduce runtime errors.
-
Maintain Readability:
-
Encapsulate Repetitive Code:
- Utilize partial views, display templates, and editor templates to reuse common UI components and reduce code duplication.
-
Leverage Razor's Features:
- Utilize Razor directives, layout pages, and sections to create modular and maintainable views.
-
Handle Nulls and Exceptions Gracefully:
Example: Using Null-Conditional Operator
<p>Email: @Model?.Email ?? "Not Provided"</p>
Explanation:
- Checks if
Model and Model.Email are not null before attempting to display the email. If Email is null, it displays "Not Provided."
Common Pitfalls
-
Mixing Business Logic with Presentation:
Incorporating business logic directly into views can lead to messy and hard-to-maintain code. It's essential to adhere to the MVC pattern by keeping concerns separated.
-
Overusing Inline Code Blocks:
Excessive use of @{ } code blocks can make the view cluttered. Strive to keep code blocks concise and refactor complex logic into helper methods or view models.
-
Neglecting HTML Encoding:
While Razor automatically encodes expressions to prevent XSS attacks, be cautious when using methods like @Html.Raw, which bypass encoding.
Example:
@Html.Raw("<strong>Bold Text</strong>")
Warning:
- Using
@Html.Raw can expose your application to XSS vulnerabilities if the content is not properly sanitized.
-
Incorrect Syntax Usage:
Misplacing the @ symbol or misusing Razor syntax can lead to unexpected behavior or render errors. Always double-check Razor syntax rules when encountering issues.
-
Not Utilizing Layouts Appropriately:
Failing to use layout pages can result in code duplication. Layouts promote reusability and consistency across views.
-
Ignoring Performance Considerations:
Rendering large datasets directly in views without pagination or optimization can degrade performance. Implement efficient data retrieval and rendering strategies.
Comprehensive Code Examples
To solidify the understanding of Razor's functionality, let's explore a series of comprehensive code examples that build upon each other, illustrating various aspects of Razor syntax and usage.
Example 1: Basic Razor Syntax
Scenario: Create a simple view that displays a static greeting message.
Code:
@{
string greeting = "Welcome to the Razor View Engine!";
}
<!DOCTYPE html>
<html>
<head>
<title>Razor Basics</title>
</head>
<body>
<h1>@greeting</h1>
@* This is a Razor comment and will not appear in the HTML *@
</body>
</html>
Explanation:
-
Code Block (@{ }): Declares a string variable greeting.
-
Razor Expression (@greeting): Inserts the value of greeting into the <h1> tag.
-
Razor Comment (@* *@): Adds a comment within the view that is not rendered in the final HTML.
Rendered Output:
<!DOCTYPE html>
<html>
<head>
<title>Razor Basics</title>
</head>
<body>
<h1>Welcome to the Razor View Engine!</h1>
</body>
</html>
Example 2: Using Variables and Expressions
Scenario: Display the current date and time with a personalized message.
Code:
@{
string userName = "Alice";
DateTime currentDate = DateTime.Now;
}
<!DOCTYPE html>
<html>
<head>
<title>User Greeting</title>
</head>
<body>
<p>Hello, @userName!</p>
<p>Current Date and Time: @currentDate.ToString("F")</p>
</body>
</html>
Explanation:
Rendered Output:
<!DOCTYPE html>
<html>
<head>
<title>User Greeting</title>
</head>
<body>
<p>Hello, Alice!</p>
<p>Current Date and Time: Friday, September 1, 2023 12:34 PM</p>
</body>
</html>
Note: The actual date and time will vary based on when the code is executed.
Example 3: Implementing Loops
Scenario: Display a list of courses available to a student.
Code:
@{
var courses = new List<string>
{
"Introduction to Programming",
"Database Systems",
"Web Development",
"Software Engineering",
"Data Structures"
};
}
<!DOCTYPE html>
<html>
<head>
<title>Available Courses</title>
</head>
<body>
<h2>Available Courses:</h2>
<ul>
@foreach (var course in courses)
{
<li>@course</li>
}
</ul>
</body>
</html>
Explanation:
-
Data Declaration:
- A list of course names is created and stored in the
courses variable.
-
@foreach Loop:
Rendered Output:
<!DOCTYPE html>
<html>
<head>
<title>Available Courses</title>
</head>
<body>
<h2>Available Courses:</h2>
<ul>
<li>Introduction to Programming</li>
<li>Database Systems</li>
<li>Web Development</li>
<li>Software Engineering</li>
<li>Data Structures</li>
</ul>
</body>
</html>
Example 4: Conditional Rendering
Scenario: Display promotional content based on the user's subscription status.
Code:
@{
string userName = "Bob";
bool isPremiumSubscriber = true;
}
<!DOCTYPE html>
<html>
<head>
<title>User Dashboard</title>
</head>
<body>
<h1>Welcome, @userName!</h1>
@if (isPremiumSubscriber)
{
<p>Thank you for being a premium subscriber! Enjoy exclusive benefits.</p>
}
else
{
<p>Upgrade to premium to access exclusive features.</p>
}
</body>
</html>
Explanation:
-
Variables:
-
Conditional Statements:
-
If isPremiumSubscriber is true, a message thanking the user for their premium subscription is displayed.
-
Otherwise, a prompt to upgrade is shown.
Rendered Output (Premium Subscriber):
<!DOCTYPE html>
<html>
<head>
<title>User Dashboard</title>
</head>
<body>
<h1>Welcome, Bob!</h1>
<p>Thank you for being a premium subscriber! Enjoy exclusive benefits.</p>
</body>
</html>
Rendered Output (Non-Premium Subscriber):
If isPremiumSubscriber is false, the output would be:
<!DOCTYPE html>
<html>
<head>
<title>User Dashboard</title>
</head>
<body>
<h1>Welcome, Bob!</h1>
<p>Upgrade to premium to access exclusive features.</p>
</body>
</html>
Example 5: Combining All Concepts
Scenario: Create a dynamic product catalog that displays products, their details, and highlights hot deals.
Model Class (for context):
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public bool IsHotDeal { get; set; }
public List<string> Features { get; set; }
}
Razor View Code:
@model MyApp.Models.ProductCatalogViewModel
@{
var catalogTitle = "Product Catalog";
}
<!DOCTYPE html>
<html>
<head>
<title>@catalogTitle</title>
<style>
.hot-deal {
color: red;
font-weight: bold;
}
.product-list {
list-style-type: none;
padding: 0;
}
.product-list li {
border: 1px solid #ccc;
margin-bottom: 10px;
padding: 10px;
}
</style>
</head>
<body>
<h1>@catalogTitle</h1>
@if (Model.Products != null && Model.Products.Any())
{
<ul class="product-list">
@foreach (var product in Model.Products)
{
<li>
<h2>
@product.Name
@if (product.IsHotDeal)
{
<span class="hot-deal">HOT DEAL!</span>
}
</h2>
<p>Price: @product.Price.ToString("C")</p>
@if (product.Features != null && product.Features.Any())
{
<p>Features:</p>
<ul>
@foreach (var feature in product.Features)
{
<li>@feature</li>
}
</ul>
}
else
{
<p>No features listed.</p>
}
</li>
}
</ul>
}
else
{
<p>No products available at the moment. Please check back later.</p>
}
@* Example of an inline function *@
@functions {
public string GetDealMessage(bool isHotDeal)
{
return isHotDeal ? "Limited time offer!" : "Available now.";
}
}
<p>@GetDealMessage(true)</p>
</body>
</html>
Explanation:
-
Model Binding:
- The view is strongly-typed with
ProductCatalogViewModel, which contains a list of Product objects.
-
Variables:
catalogTitle sets the title of the catalog.
-
Conditional Rendering:
-
Checks if the Products list is not null and contains items.
-
If products are available, it renders each product; otherwise, it displays a message indicating no products are available.
-
Loops:
-
Nested Conditionals:
-
Within the product loop, an @if statement checks if the product is marked as a hot deal, displaying a "HOT DEAL!" badge if true.
-
Another @if checks if the product has features to display the features list or a message indicating no features.
-
Inline Function:
Rendered Output:
Assuming the ProductCatalogViewModel contains the following data:
public class ProductCatalogViewModel
{
public List<Product> Products { get; set; }
}
// Sample Data:
var viewModel = new ProductCatalogViewModel
{
Products = new List<Product>
{
new Product
{
Name = "Gaming Laptop",
Price = 1299.99m,
IsHotDeal = true,
Features = new List<string> { "16GB RAM", "RTX 3060", "1TB SSD" }
},
new Product
{
Name = "Wireless Mouse",
Price = 49.99m,
IsHotDeal = false,
Features = new List<string> { "Ergonomic Design", "2.4 GHz Wireless" }
}
}
};
Resulting HTML:
<!DOCTYPE html>
<html>
<head>
<title>Product Catalog</title>
<style>
.hot-deal {
color: red;
font-weight: bold;
}
.product-list {
list-style-type: none;
padding: 0;
}
.product-list li {
border: 1px solid #ccc;
margin-bottom: 10px;
padding: 10px;
}
</style>
</head>
<body>
<h1>Product Catalog</h1>
<ul class="product-list">
<li>
<h2>
Gaming Laptop
<span class="hot-deal">HOT DEAL!</span>
</h2>
<p>Price: $1,299.99</p>
<p>Features:</p>
<ul>
<li>16GB RAM</li>
<li>RTX 3060</li>
<li>1TB SSD</li>
</ul>
</li>
<li>
<h2>
Wireless Mouse
</h2>
<p>Price: $49.99</p>
<p>Features:</p>
<ul>
<li>Ergonomic Design</li>
<li>2.4 GHz Wireless</li>
</ul>
</li>
</ul>
<p>Limited time offer!</p>
</body>
</html>
Key Observations:
-
Dynamic Content Rendering: The view dynamically renders product information based on the data provided by the model.
-
Conditional Badging: The "HOT DEAL!" badge is only displayed for products marked as hot deals.
-
Nested Lists: Features for each product are displayed as nested lists, showcasing the flexibility of Razor's looping constructs.
-
Inline Function Usage: Demonstrates how to define and use inline functions within the view for reusable logic.
Summary
The Razor View Engine is a powerful tool within the ASP.NET MVC framework that enables developers to create dynamic, maintainable, and efficient web pages by seamlessly integrating server-side code with client-side markup. Through this section, we've explored the foundational concepts of Razor, including its syntax, directives, and the practical application of embedding C# code within HTML.
Key Takeaways:
-
Seamless Integration: Razor allows for the straightforward blending of C# code and HTML, fostering the creation of dynamic and responsive web pages.
-
Concise Syntax: Razor's lightweight syntax reduces verbosity, enhancing code readability and maintainability.
-
Control Flow Constructs: With loops and conditionals, developers can render content based on data and application state, ensuring that users receive the most relevant information.
-
Best Practices: Maintaining a clear separation of concerns, minimizing logic in views, and leveraging Razor's features judiciously contribute to building robust and scalable applications.
By mastering the Razor View Engine, you empower yourself to build sophisticated web interfaces that are both functional and elegant, adhering to the best practices of modern web development.