Chapter 23: Razor – C# Logic Conditions
Razor: C# Logic Conditions (if, else, switch, ternary operators, null checks, etc.) inside .cshtml files.
This is where your pages become truly intelligent: showing different content depending on time of day, user role, whether something exists, stock status, user login state, form validation results — basically any decision that changes what HTML gets sent to the browser.
I will explain it like we’re sitting together in a small café near Charminar, writing code on napkins, testing mentally, and seeing how Razor makes conditions feel natural and clean.
1. Why Conditions Are So Important in Razor
In almost every real website:
- Greet user differently: “Good morning” vs “Good evening”
- Show “Add to Cart” only if in stock
- Display login form vs “Welcome back, Rahul” after login
- Show error message only if form failed
- Highlight active menu item
- Show “No results” when search returns empty
- Apply red/green styling based on positive/negative value
Razor + C# conditions let you do all of this without messy string concatenation or separate templates.
2. The Four Main Ways to Write Conditions in Razor Markup
A. @if … else (Most common – full control)
|
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 |
@{ var hour = DateTime.Now.Hour; var isAdmin = User.IsInRole("Admin"); var cartCount = 3; // imagine from Session or DB } <div class="greeting"> @if (hour < 12) { <span>Good Morning! ☀️</span> } else if (hour < 17) { <span>Good Afternoon! 🌤️</span> } else { <span>Good Evening! 🌙</span> } @if (isAdmin) { <a href="/Admin/Dashboard" class="admin-link">Admin Panel</a> } </div> @if (cartCount > 0) { <span class="cart-badge">@cartCount</span> } else { <span class="cart-empty">Cart is empty</span> } |
→ Razor knows that after @if { … } the <span> is HTML again — no need to close anything manually.
B. Inline ternary operator – @(condition ? value1 : value2)
Very popular for small decisions (class names, text, visibility)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
@{ var inStock = true; var price = 399m; var discount = 20; var finalPrice = price * (1 - discount / 100m); } <button class="@(inStock ? "btn-success" : "btn-secondary disabled")"> @(inStock ? "Add to Cart – ₹" + finalPrice.ToString("N0") : "Out of Stock") </button> <div class="stock @(inStock ? "text-success" : "text-danger")"> @(inStock ? "In Stock" : "Currently Unavailable") </div> |
→ Short, clean, perfect for attributes, text, classes.
C. Null-conditional / null-coalescing operators (C# 6+ features – very common in Razor)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@{ string userName = null; // imagine from session or DB var cartItems = new List<string>(); // empty } <p>Hello @(userName ?? "Guest")!</p> <!-- Null-conditional: safe access --> <p>Cart has @(cartItems?.Count ?? 0) items</p> <!-- Null-coalescing assignment (C# 8+) --> @{ userName ??= "Anonymous"; } <p>Welcome back, @userName!</p> |
→ Prevents NullReferenceException when data might be missing (very frequent in real apps).
D. @switch (less common, but useful for multiple fixed choices)
|
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 |
@{ var day = DateTime.Today.DayOfWeek; } <div class="day-message"> @switch (day) { case DayOfWeek.Monday: <p>Motivation Monday! 💪</p> break; case DayOfWeek.Friday: <p>Friday vibes! 🎉</p> break; case DayOfWeek.Saturday: case DayOfWeek.Sunday: <p>Weekend mode ON! 🏖️</p> break; default: <p>Keep going — it's @day!</p> break; } </div> |
3. Full Realistic Example – E-commerce Product Card with Lots of Conditions
|
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 68 69 70 71 72 73 74 75 76 77 78 79 80 |
@{ var product = new { Name = "Hyderabadi Dum Biryani (Family Pack)", Price = 699m, DiscountPercent = 15, Rating = 4.7, ReviewCount = 842, IsInStock = true, IsNew = true, Tags = new[] { "Non-Veg", "Spicy", "Bestseller" } }; var finalPrice = product.Price * (1 - product.DiscountPercent / 100m); } <div class="product-card"> @if (product.IsNew) { <span class="badge-new">NEW</span> } <h3>@product.Name</h3> <div class="price-block"> <span class="current-price">₹@finalPrice.ToString("N0")</span> @if (product.DiscountPercent > 0) { <span class="original-price">₹@product.Price.ToString("N0")</span> <span class="discount">(@product.DiscountPercent% OFF)</span> } </div> <div class="rating"> @for (int i = 1; i <= 5; i++) { <span class="@(i <= Math.Round(product.Rating) ? "star filled" : "star empty")">★</span> } <span>(@product.ReviewCount)</span> </div> <p class="stock @(product.IsInStock ? "in-stock" : "out-of-stock")"> @(product.IsInStock ? "In Stock – Ready to Ship" : "Out of Stock") </p> <div class="tags"> @foreach (var tag in product.Tags) { <span class="tag">@tag</span> } </div> @if (product.IsInStock) { <button class="btn-add">Add to Cart</button> } else { <button class="btn-notify" disabled>Notify Me When Available</button> } </div> <style> .product-card { border: 1px solid #eee; padding: 20px; max-width: 350px; position: relative; } .badge-new { position: absolute; top: 10px; right: 10px; background: #ff6b6b; color: white; padding: 4px 8px; border-radius: 4px; font-size: 0.8em; } .current-price { font-size: 1.6em; color: #e44d26; font-weight: bold; } .original-price { text-decoration: line-through; color: #999; margin-left: 10px; } .discount { color: #28a745; font-weight: bold; margin-left: 10px; } .star.filled { color: gold; } .in-stock { color: #28a745; font-weight: bold; } .out-of-stock { color: #dc3545; font-weight: bold; } .tag { background: #f0f0f0; padding: 4px 10px; margin-right: 6px; border-radius: 12px; font-size: 0.85em; } .btn-add { background: #28a745; color: white; border: none; padding: 10px 20px; cursor: pointer; } .btn-notify { background: #6c757d; color: white; border: none; padding: 10px 20px; cursor: not-allowed; } </style> |
4. Teacher Summary – What to Remember
ASP.NET Razor – C# Logic Conditions means:
- @if / else if / else { HTML } → full blocks of conditional HTML
- @(condition ? value1 : value2) → inline decisions (classes, text, attributes)
- ?. and ?? → safe null handling (prevents crashes)
- @switch { case … : … break; } → for multiple fixed choices
- Conditions live inside@if { … } or @(…) and control what HTML gets rendered
Master these four patterns and you can make your pages smart, personalized, and adaptive.
Next class?
- Want to see conditions + loops together (e.g., filter list + conditional rows)?
- Or conditions in forms (validation messages, pre-filled values)?
- Or how conditions work with login state (User.Identity.IsAuthenticated)?
- Or jump to @model and conditions on model properties?
Just tell me — you’re building real Razor superpowers in Hyderabad! 🚀🇮🇳 Keep going! 😊
