Adding Conditional Content
Explore how to use conditional statements in Razor templates to dynamically control HTML output in ASP.NET Core MVC. Understand the correct use of C# if, else, else if, and switch statements alongside HTML, managing null values, and the syntax rules between HTML and C# modes. Master the implementation of conditional sections in layout pages to optimize content like JavaScript or CSS references. This lesson helps you create adaptable, clean, and maintainable web UI content tailored to your data.
We'll cover the following...
Conditional statements
Sometimes filling holes in HTML with variable content is not enough to adapt the HTML to our data. We might need to include some HTML only if some conditions are met. A typical example is the proper handling of null values or empty lists:
Conditional content may be provided with a usual C# if statement and precedes with an @ symbol. Similar to the case of C# expressions, the @ symbol informs the Razor compiler that we are passing from HTML syntax to C# syntax.
We may also add an else branch:
We may also add else if branches, so the general statement format is:
Razor syntax also supports the switch statement:
The content between the { and } symbols of the if branches and the content after each case of the switch can be a mix of C# code and HTML. In the previous examples, we started ...