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)

HTML

→ 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)

HTML

→ Short, clean, perfect for attributes, text, classes.

C. Null-conditional / null-coalescing operators (C# 6+ features – very common in Razor)

HTML

→ Prevents NullReferenceException when data might be missing (very frequent in real apps).

D. @switch (less common, but useful for multiple fixed choices)

HTML

3. Full Realistic Example – E-commerce Product Card with Lots of Conditions

HTML

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! 😊

You may also like...

Leave a Reply

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