Skip to main content
Home  › ... Razor

Basic Tutorials

Tutorial HomeBasics
#2 Conditions

Using if and if-else

Basic if

Output

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

If-Else

Output

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

Using if-else and <text> tags

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

Output

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

Quick if-else using Ternary operator ? :

Output

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

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@inherits Custom.Hybrid.Razor14
<!-- unimportant stuff, hidden -->


<div @Sys.PageParts.InfoWrapper()>
  @Html.Partial("../shared/DefaultInfoSection.cshtml")
  <div @Sys.PageParts.InfoIntro()>
    <h2>Using if and if-else</h2>
  </div>
</div>


<h3>Basic <code>if</code></h3>

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



<h3>If-Else</h3>

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



<h3>Using if-else and <code>&lt;text&gt;</code> tags</h3>
<p>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</p>

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



<h3>Quick if-else using Ternary operator <code>? :</code></h3>

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



@* Footer *@
@Html.Partial("../Shared/Layout/FooterWithSource.cshtml", new { Sys = Sys })