โœจ ASP.NET Razor Syntax
Estimated reading: 3 minutes 31 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ”ค Razor C# โ€“ Variables

Or Copy Link

CONTENTS
Scroll to Top