Blazor if, else and else if

if, else and else if are conditional statements that are used to execute different block of codes depending on different conditions.

In the following, the item "Check in" is displayed if the condition "@item is not null" is true.

@page "/"

@if (item == null)
{
    <p>Error</p>
}
else
{
    @item
}

@functions {
    string item = "Check in";

}


Syntax


if (condition) {
    block of code to be executed if the condition is true
} 

if (condition) {
    block of code to be executed if the condition is true
} else { 
    block of code to be executed if the condition is false
}

if (condition1) {
    block of code to be executed if condition1 is true
} else if (condition2) {
    block of code to be executed if the condition1 is false and condition2 is true
} else {
    block of code to be executed if the condition1 is false and condition2 is false
}

Expanding on the example to add in else if.

@page "/"

@if (items == null)
{
  <p>Error</p>
}
else if (items.Length == 1)
{
  @items[0]
}
else
{
  <ul>
  @foreach (var item in items)
  {
      <li>
          @item
      </li>
  }
  </ul>
}

@functions {
	string[] items = { "Check in", "Unpack" };
}

The above will give you the following:

<ul>
    <li>Check in</li>
    <li>Unpack</li>
</ul>