Chapter 21: Razor – C# Variables
Razor – C# Variables — that is, how you declare, use, and work with variables inside .cshtml Razor files when using C#.
This is one of the first things every Razor beginner must master, because almost every dynamic page starts with variables: names, prices, dates, lists, user data, flags, calculations, etc.
I’m going to explain it like we’re sitting together at a table in Charminar area, writing code on paper, running it mentally, and debugging together — very slowly, with lots of real examples.
1. The Golden Rule of Variables in Razor (Write this down!)
In Razor .cshtml files using C#:
- Variables are declared and used exactly the same way as in normal C# — same rules, same types, same scope rules.
- The only difference is where you place them:
- Inside @{ … } code blocks → normal C# variables (most common)
- Inline with @ → you can use them directly in HTML output
There is no special “Razor variable type” — they are pure C# variables.
2. Three Main Places Where You Meet Variables in Razor
Place 1 – Code Blocks at the Top (Most Common)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@{ // This is a normal C# code block — everything here is pure C# string city = "Hyderabad"; int temperature = 33; decimal price = 299.99m; bool isWeekend = DateTime.Today.DayOfWeek == DayOfWeek.Saturday || DateTime.Today.DayOfWeek == DayOfWeek.Sunday; DateTime today = DateTime.Today; var message = $"Welcome to {city}! Today is {today:dddd, dd MMMM yyyy}."; var foods = new List<string> { "Biryani", "Haleem", "Irani Chai" }; } |
→ Rules inside @{ … }:
- Use var (implicit typing — most popular) or explicit types (string, int, decimal, etc.)
- End statements with ;
- Case-sensitive (city ≠ City)
- Normal C# scope: variables declared here are available below in the same file (and in layouts/sections if passed via Page or ViewData)
Place 2 – Inline Expressions with @
Once declared, you can use variables anywhere in HTML with just @:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<p>Hello from @city! Current temperature: @temperature°C</p> <p>Price: ₹@price</p> <p>Is today weekend? @(isWeekend ? "Yes! 🎉" : "No, work day")</p> <p>@message</p> <ul> @foreach (var food in foods) { <li>@food.ToUpper()</li> } </ul> |
→ @variableName → Razor evaluates it and prints .ToString() result → @(expression) → use parentheses when it’s a calculation or complex expression
Place 3 – Sharing Variables with Layout / Partial Views
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
@{ // In content page Layout = "~/Shared/_Layout.cshtml"; Page.Title = "Home Page"; Page.ActiveMenu = "home"; Page.UserCount = 1420; } <!-- In _Layout.cshtml --> <title>@Page.Title - My Hyderabad Site</title> <span>Active users now: @Page.UserCount</span> <a class="@(Page.ActiveMenu == "home" ? "active" : "")" href="/">Home</a> |
→ Page is a dynamic object — you can add any property you want (Page.anything = value;)
3. Common Variable Types & How They Look in Razor
| Type | Declaration Example | Output Example | Notes / Gotchas |
|---|---|---|---|
| string | var name = “Rahul”; | @name → Rahul | Most common |
| int | var age = 25; | @age → 25 | Use AsInt() when reading from form |
| decimal | var price = 499.99m; | @price.ToString(“C”) → ₹499.99 | m suffix for literal |
| bool | var isLoggedIn = true; | @(isLoggedIn ? “Yes” : “No”) | Ternary is very common |
| DateTime | var now = DateTime.Now; | @now.ToString(“dd-MMM-yyyy”) | Formatting is important |
| List<T> | var items = new List<string> { “A”, “B” }; | @foreach (var i in items) { … } | Most used collection |
| var (implicit) | var data = db.Query(…); | @data.Count() | Razor loves var |
4. Full Realistic Example – Mini Product Card Page
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
@{ // 1. Declare variables (realistic e-commerce scenario) var productName = "Hyderabadi Dum Biryani"; var price = 399.00m; var rating = 4.7; var reviewsCount = 1284; var isInStock = true; var discount = 15; // percent var discountedPrice = price * (1 - discount / 100m); var tags = new[] { "Non-Veg", "Spicy", "Popular", "Weekend Special" }; var stockMessage = isInStock ? "In Stock" : "Out of Stock"; var stockColor = isInStock ? "green" : "red"; } <!DOCTYPE html> <html> <head> <title>@productName - Webliance Shop</title> <style> .card { border: 1px solid #ddd; padding: 20px; max-width: 400px; margin: 20px auto; } .price { font-size: 1.8em; color: #e44d26; } .stock { color: @stockColor; font-weight: bold; } </style> </head> <body> <div class="card"> <h2>@productName</h2> <p class="price"> ₹@discountedPrice.ToString("N2") <small>(@discount% OFF)</small> </p> <p>Original: ₹@price.ToString("N2")</p> <p>Rating: @rating ★★★★☆ (@reviewsCount reviews)</p> <p class="stock">@stockMessage</p> <div> Tags: @foreach (var tag in tags) { <span style="background:#eee; padding:4px 8px; margin-right:6px; border-radius:4px;"> @tag </span> } </div> @if (isInStock) { <button style="background:#28a745; color:white; padding:10px 20px; border:none; margin-top:15px;"> Add to Cart </button> } </div> </body> </html> |
→ Every line shows variables being:
- Declared (var …)
- Calculated (discountedPrice = …)
- Formatted (.ToString(“N2”), .ToString(“C”))
- Used in conditions (@if (isInStock))
- Looped (@foreach)
- Printed (@productName, @discountedPrice, etc.)
5. Teacher Tips & Common Beginner Mistakes
- Always declare variables before using them in HTML (top-to-bottom execution)
- Use var most of the time — cleaner and Razor-friendly
- For money → always use decimal (not double — floating point issues)
- When reading from forms: int qty = Request[“qty”].AsInt(0); — never trust Convert.ToInt32()
- Scope: variables in @{ } at top are available everywhere below in the same file
- Avoid very long code blocks — keep logic clean, move complex code to PageModel (in modern Razor Pages)
Summary – Blackboard Close
ASP.NET Razor – C# Variables means:
- Declare them exactly like normal C# (var x = value;, string name = “Hyderabad”;, int count = 42;)
- Use @{ … } blocks at the top of the file for logic & declarations
- Print/use them anywhere in HTML with simple @variable or @(expression)
- Share between page & layout using Page.variableName = value;
- Razor treats them as normal C# variables — no special magic type
Now you can create, calculate, format, loop, and display any data you want!
Next step?
- Want to see how variables work with forms (reading from Request)?
- Or variables in loops & conditions with more examples?
- Or move to @model and strongly-typed variables in Razor Pages?
Just tell me — you’re doing great! Keep coding strong from Hyderabad! 🚀🇮🇳
