ASP.NET Razor – C# Variables

Welcome to The Coding College, your trusted source for coding and programming tutorials. In this guide, we’ll explore how to declare, use, and manage C# variables in ASP.NET Razor, enabling you to build dynamic and efficient web pages.

What Are Variables in Razor?

In Razor syntax, variables are placeholders used to store data during the execution of server-side code. Razor uses C# variables to process logic and dynamically generate HTML content.

Declaring Variables in Razor

Variables in Razor are declared using the var keyword or specific data types like int, string, or bool.

1. Using var (Implicit Typing)

The var keyword allows you to declare variables without specifying their exact type.

@{
    var name = "John";
    var age = 25;
    var isActive = true;
}
<p>Name: @name</p>
<p>Age: @age</p>
<p>Active: @isActive</p>

2. Using Explicit Typing

You can declare variables with specific data types for better type control.

@{
    string name = "John";
    int age = 25;
    bool isActive = true;
}
<p>Name: @name</p>
<p>Age: @age</p>
<p>Active: @isActive</p>

Variable Scope in Razor

Variables in Razor follow the same scoping rules as C#.

1. Local Scope

Variables declared inside a Razor block (@{ ... }) are only accessible within that block.

@{
    var localMessage = "This is local.";
}
<p>@localMessage</p>

2. Page-Level Scope

Variables declared outside Razor blocks are accessible across the entire page.

@{
    string pageMessage = "This is accessible across the page.";
}
<p>@pageMessage</p>

Using Variables with HTML Content

Razor variables can be dynamically inserted into HTML elements.

Example: Dynamic Content

@{
    string greeting = "Welcome to The Coding College!";
}
<h1>@greeting</h1>

Example: Dynamic Attributes

@{
    bool isActive = true;
}
<div class="menu-item @(isActive ? "active" : "")">Home</div>

Common Variable Operations

1. String Concatenation

Combine strings dynamically using the + operator or string interpolation.

@{
    string firstName = "John";
    string lastName = "Doe";
}
<p>Full Name: @($"{firstName} {lastName}")</p>

2. Mathematical Operations

Perform calculations using Razor variables.

@{
    int a = 10;
    int b = 20;
    int sum = a + b;
}
<p>Sum: @sum</p>

3. Conditional Values

Set variables conditionally using the ternary operator.

@{
    int age = 18;
    string status = (age >= 18) ? "Adult" : "Minor";
}
<p>Status: @status</p>

Using Variables in Loops

Variables often play a key role in loops, enabling you to iterate through data.

Example: Looping Through an Array

@{
    string[] fruits = { "Apple", "Banana", "Cherry" };
}
<ul>
    @foreach (var fruit in fruits)
    {
        <li>@fruit</li>
    }
</ul>

Best Practices for Using Variables in Razor

  • Use Meaningful Names
    Always name variables descriptively to make your code more readable.
string userFirstName = "John"; // Descriptive
string uf = "John"; // Not Descriptive
  • Minimize Scope
    Declare variables in the narrowest scope needed to avoid unintended modifications.
  • Use Explicit Types When Necessary
    While var is convenient, use explicit types for clarity in complex scenarios.
  • Initialize Variables Properly
    Always initialize variables to avoid runtime errors.

HTML Encoding with Razor Variables

Razor automatically encodes variable output to prevent cross-site scripting (XSS).

Example: Automatic Encoding

@{
    string script = "<script>alert('Hello!')</script>";
}
<p>@script</p> <!-- Output: <script>alert('Hello!')</script> -->

To render raw HTML, use Html.Raw:

<p>@Html.Raw(script)</p> <!-- Output: <script>alert('Hello!')</script> -->

Common Mistakes to Avoid

  1. Forgetting to Initialize Variables
    Uninitialized variables can cause compilation errors.
  2. Using Reserved Keywords
    Avoid naming variables after reserved C# keywords like int, class, or namespace.
  3. Ignoring Encoding
    Never output raw content without proper encoding unless absolutely necessary.

Why Master C# Variables in Razor?

Variables are fundamental to dynamic web development. Understanding how to declare, manipulate, and secure variables in ASP.NET Razor ensures you can build robust, efficient, and secure web pages.

Learn More at The Coding College

At The Coding College, we’re committed to helping you master web development. Ready to level up your skills? Explore more ASP.NET Razor tutorials on our website and start building better applications today.

Have questions or need clarification? Drop a comment below, or visit The Coding College for more tutorials to enhance your coding skills.

Leave a Comment