Skip to main content
Home  › ... Razor

Razor Basics Tutorials

Tutorial HomeRazor Basics
#2 Razor Conditions such as if, if-else and ? :
The samples can differ based on your Razor base class or if you're running an old version.
Switch to Strong-Typed (2sxc 17.06+) Switch to Typed (2sxc 16+) Selected: Dynamic (Razor14 or below)

Razor Conditions such as if, if-else and ? :

⬇️ Result | Source ➡️

it's green
@inherits Custom.Hybrid.RazorTyped

@{
  var aValue = "green";
}
@if (aValue == "green") {
  <span>it's green </span>
}

⬇️ Result | Source ➡️

it's blue
@inherits Custom.Hybrid.RazorTyped

@{
  var val2 = "blue";
}
@if (val2 == "green") {
  <span>it's green </span>
} else {
  <span>it's blue</span>
}

This is important, if you have an code block like an if, and you don't want a span-tag or similar in the output

⬇️ Result | Source ➡️

it's not pink
@inherits Custom.Hybrid.RazorTyped

@{
  var val4 = "orange";
}
@if (val4 != "pink") {
  <text>it's not pink</text>
}

⬇️ Result | Source ➡️

it's not red
@inherits Custom.Hybrid.RazorTyped

@{
  var val3 = "blue";
}
@(val3 == "red" ? "it's red" : "it's not red")

⬇️ Result | Source ➡️

Day of week: Sunday
It's the weekend

It's the weekend 🥳

@inherits Custom.Hybrid.RazorTyped

@{
  var dayOfWeek = DateTime.Now.DayOfWeek;
  var message = "";
  // use switch to show workdays and weekend
  switch (dayOfWeek)
  {
    case DayOfWeek.Monday:
    case DayOfWeek.Tuesday:
    case DayOfWeek.Wednesday:
    case DayOfWeek.Thursday:
    case DayOfWeek.Friday:
      message = "It's a workday";
      break;
    case DayOfWeek.Saturday:
    case DayOfWeek.Sunday:
      message = "It's the weekend";
      break;
  }
}
Day of week: @dayOfWeek
<br>
@message


@switch (dayOfWeek)
{
  case DayOfWeek.Monday:
    <p>It's a tough workday 💪🏾</p>
    break;
  case DayOfWeek.Tuesday:
  case DayOfWeek.Wednesday:
  case DayOfWeek.Thursday:
    <p>It's a workday</p>
    break;
  case DayOfWeek.Friday:
    <p>It's the best workday 🏖️</p>
    break;
  case DayOfWeek.Saturday:
  case DayOfWeek.Sunday:
    <p>It's the weekend 🥳</p>
    break;
}

⬇️ Result | Source ➡️

Title: Title not provided
@inherits Custom.Hybrid.RazorTyped

@{
  // Let's assume you have a property to which you don't know if it was set or not
  // so it will be null in this example
  var title = MyModel.String("Title", required: false)
    ?? "Title not provided";
}
Title: @title

 

#2 Razor Conditions such as if, if-else and ? :