Razor Syntax and Views
Razor
Razor is one of the view engines supported when creating a MVC .net Core app. Razor allows for the mixing of HTML and server-side code using C# or Visual Basic. Most commonly developers use C#.
The Microsoft site provides full documentation:
Open the Views/News/Index.cshtml previously created to experiment with Razor.
Razor Expressions @ Symbol
Razor supports C# and uses the @ symbol within a view to transition from HTML to C#. Razor evaluates C# expressions and renders them in the HTML output.
Note: In email address @ acts as HTML. If needed in the text outside of an email the @ can be escaped with @@.
To format the date differently use ToString.
Code after @ is rendered directly to the view and therefore must be valid C#.
Razor Code Blocks
Blocks of Razor Code Blocks are added with @{ ... }. Code in blocks is not rendered and most frequently used for variable declartions.
The variable could then be rendered in the view with the @.
Explict Razor Expressions
Explicit Razor expressions consist of an @(....). Content within the @(....) parenthesis is evaluated and rendered to the output.
Be careful to remove any superfluous whitespace in the expression.
Conditional Statements
Conditional statements can be built with @if, else if, else, and @switch
Loops
Loops can be built from @for, @foreach, @while, and @do while
Loops can be performed around Arrays.
Generally considered good practice to place data in the Controller (more later) but Lists can be declared in the view and looped.
The following build a drop-down list of the months of the year.
Challenge: Can you make this a drop-down list.
Later we'll see how information from a database can be stored in a model and passed to the view.