MVC: Razor Views

Menu
Menu

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.

Place in View

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.

Place in View

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.

Place in View

The variable could then be rendered in the view with the @.

Place in View

Explict Razor Expressions

Explicit Razor expressions consist of an @(....). Content within the @(....) parenthesis is evaluated and rendered to the output.

Place in View

Be careful to remove any superfluous whitespace in the expression.

Conditional Statements

Conditional statements can be built with @if, else if, else, and @switch

Place in View

Loops

Loops can be built from @for, @foreach, @while, and @do while

Place in View

Loops can be performed around Arrays.

Place in View

Generally considered good practice to place data in the Controller (more later) but Lists can be declared in the view and looped.

Place in View

The following build a drop-down list of the months of the year.

Challenge: Can you make this a drop-down list.

Place in View

Later we'll see how information from a database can be stored in a model and passed to the view.

Place in View