โœจ ASP.NET Razor Syntax
Estimated reading: 3 minutes 427 views

Razor C# โ€“ Variables โ€“ Declare and Use Variables in Razor Views

Introduction โ€“ What Are Razor Variables?

In Razor syntax, variables allow you to store and manipulate data inside .cshtml views using C#. You can use them to hold strings, numbers, lists, objects, or even results of calculations and conditions. Razor variables are commonly used in templates to display dynamic content.

In this guide, youโ€™ll learn:

  • How to declare variables in Razor
  • Different ways to use variables inline or in code blocks
  • Practical examples of variable usage in views
  • Best practices for using variables efficiently in Razor pages

Declaring Variables in Razor

Use @{ ... } code blocks to define variables in Razor views.

@{
    string name = "Vaibhav";
    int age = 28;
}
<p>Name: @name</p>
<p>Age: @age</p>

Output:

Name: Vaibhav  
Age: 28

Example โ€“ Variable in Expressions

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

Razor renders @sum as 30.


Variable Inside Loops and Conditions

You can declare and update variables inside loops and conditionals:

@{
    int counter = 1;
}
<ul>
@while (counter <= 3)
{
    <li>Item @counter</li>
    counter++;
}
</ul>

Output:

Item 1  
Item 2  
Item 3

Working with String Interpolation

@{
    string product = "Laptop";
    int price = 50000;
}
<p>@($"Product: {product}, Price: โ‚น{price}")</p>

Output: Product: Laptop, Price: โ‚น50000


Declaring Complex Variables (Arrays, Lists)

@{
    string[] colors = { "Red", "Green", "Blue" };
}
@foreach (var color in colors)
{
    <p>@color</p>
}

You can also use:

  • List<string>
  • Dictionary<TKey, TValue>
  • Custom model types

Scope of Razor Variables

LocationScope Description
Inside @{}Local to the block/view
Inside @functionsReusable methods and shared variables
In @model propertiesPassed from controller or page model

Setting Variables Dynamically

@{
    string greeting = DateTime.Now.Hour < 12 ? "Good morning" : "Good evening";
}
<p>@greeting</p>

Output depends on the server time.


Common Mistakes to Avoid

Mistake Correct Usage
string name = "John" outside @{}Use @{ string name = "John"; }
Using @ inside @{} unnecessarilyAvoid @name inside code blocks
Omitting ; in code linesEnd all C# lines in Razor with ;

Best Practices for Razor Variables

Do:

  • Keep variable names clear and descriptive
  • Use inline expressions (@variable) for simple outputs
  • Separate logic-heavy variables into the controller or page model

Avoid:

  • Placing business logic in Razor views
  • Re-declaring variables inside loops unless needed
  • Using ViewBag excessively when you have @model

Summary โ€“ Recap & Next Steps

Razor variables let you work with C# inside your views for displaying dynamic data, performing calculations, and looping through lists. They improve readability and control within .cshtml pages.

Key Takeaways:

  • Declare variables in @{} and render with @variable
  • Use variables inside loops, conditions, and interpolations
  • Keep Razor logic simple and clean

Real-world Use Cases:

  • Displaying user profile info
  • Looping through product lists
  • Conditionally formatting UI content

FAQs โ€“ Razor C# Variables


Can I declare variables outside @{} in Razor?
No. All C# variables must be declared within a Razor code block using @{}.


How do I access variables defined in the controller?
Use @model to strongly type the view and access properties via Model.PropertyName.


Can I use var to declare variables in Razor?
Yes. You can use var name = "John"; just like in C#.


How do I combine strings in Razor?
Use either + operator or string interpolation: @("Name: " + name) or $"Name: {name}".


Share Now :
Share

๐Ÿ”ค Razor C# โ€“ Variables

Or Copy Link

CONTENTS
Scroll to Top