ASP.NET Web Pages – Adding Razor Code

Welcome to The Coding College, where we empower developers to master programming concepts through hands-on tutorials! In this guide, we’ll focus on adding Razor code to your ASP.NET Web Pages. Razor is a lightweight syntax that combines HTML with server-side C# or VB.NET, making web development more dynamic and efficient.

If you’re ready to take your web pages to the next level, let’s dive in!

What is Razor Code?

Razor is a server-side markup syntax introduced in ASP.NET to simplify dynamic web development. With Razor, you can:

  • Embed server-side code directly into HTML.
  • Dynamically generate content based on server logic.
  • Use a clean, concise syntax that’s easy to learn and maintain.

Razor files typically have a .cshtml extension and seamlessly integrate with C# or VB.NET code.

Setting Up Razor in ASP.NET Web Pages

Prerequisites

  • Install Visual Studio (Community Edition is free).
  • Set up a new ASP.NET Web Pages project.

Create a Razor Page

  1. Open your project in Visual Studio.
  2. Right-click on your project in the Solution Explorer and select Add > New Item.
  3. Choose Razor Page and name it Example.cshtml.

Using Razor Code in ASP.NET Web Pages

1. Embedding Server-Side Code

Razor uses the @ symbol to switch between HTML and server-side code.

Here’s an example of embedding a simple message and current date:

@{
    var message = "Welcome to Razor!";
    var currentDate = DateTime.Now;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Razor Example</title>
</head>
<body>
    <h1>@message</h1>
    <p>Today's date is @currentDate</p>
</body>
</html>

Explanation:

  • @{}: Used to define server-side code blocks.
  • @message: Outputs the variable value directly in HTML.
  • @currentDate: Displays the current server date.

2. Conditional Logic

Razor allows you to include conditional statements to display content dynamically.

@{
    var isLoggedIn = true;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Conditional Example</title>
</head>
<body>
    @if (isLoggedIn)
    {
        <p>Welcome back, user!</p>
    }
    else
    {
        <p>Please log in to continue.</p>
    }
</body>
</html>

Explanation:

  • Use @if and @else for conditional rendering of HTML elements.

3. Loops in Razor

You can iterate through data collections and display dynamic content:

@{
    var fruits = new List<string> { "Apple", "Banana", "Cherry" };
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Loop Example</title>
</head>
<body>
    <h2>Fruits List:</h2>
    <ul>
        @foreach (var fruit in fruits)
        {
            <li>@fruit</li>
        }
    </ul>
</body>
</html>

Explanation:

  • @foreach is used to loop through a collection.
  • The <li>@fruit</li> dynamically generates list items for each fruit.

Handling Forms with Razor Code

ASP.NET Web Pages make it easy to process forms using Razor. Here’s an example of a simple feedback form:

Step 1: Create the Form

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Feedback Form</title>
</head>
<body>
    <h2>Feedback Form</h2>
    <form method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" />
        <br />
        <label for="message">Message:</label>
        <textarea id="message" name="message"></textarea>
        <br />
        <button type="submit">Submit</button>
    </form>

    @if (IsPost)
    {
        var userName = Request["name"];
        var userMessage = Request["message"];
        <p>Thank you, @userName, for your message:</p>
        <blockquote>@userMessage</blockquote>
    }
</body>
</html>

Explanation:

  • IsPost: Checks if the form was submitted.
  • Request["name"]: Retrieves the submitted form data.

Best Practices for Razor Code

  1. Keep It Clean: Use Razor to simplify server-side logic but avoid cluttering with excessive code.
  2. Reuse Code: Use helper methods or partial views for reusable code blocks.
  3. Optimize for Performance: Cache frequently used data to reduce server load.
  4. Follow Security Practices: Always validate and sanitize user inputs to prevent security vulnerabilities.

Why Learn Razor with The Coding College?

At The Coding College, we provide practical tutorials to help you gain hands-on experience with Razor and other ASP.NET features. Our step-by-step guides are perfect for both beginners and experienced developers.

With Razor, you’ll unlock the potential to build dynamic, data-driven web applications effortlessly. Explore more on ASP.NET Web Pages and Razor code at The Coding College.

Frequently Asked Questions (FAQs)

1. What is Razor’s main advantage in ASP.NET?
Razor’s main advantage is its simplicity and seamless integration of server-side logic with HTML, allowing for dynamic content generation.

2. Can I use Razor with other ASP.NET frameworks?
Yes, Razor is widely used in frameworks like MVC and Razor Pages, making it a versatile choice for ASP.NET development.

3. Is Razor syntax difficult to learn?
Not at all! Razor uses a concise syntax that’s easy for beginners to grasp, especially if you have basic knowledge of C# or VB.NET.

Leave a Comment