HTML Templates, and Dynamic Content
In this lesson, we define holes in the HTML templates that Razor will fill with variable content.
Main blocks in Razor files
Each Razor file is made of three blocks:
- An initial directives block containing
@
directives like@page
and@using
. Later on, in this course, we will see other important directives. - A template block that contains a mix of HTML and C# statements and expressions.
- A
@functions
block. In independent Razor pages, this block is necessary for defining the page’sGET
andPOST
handlers, but it can be also used for defining utility members in Razor views invoked by controllers.
Below is a summary of the structure of a Razor file:
@Page@using MyNameSpace@......<div>...<!--This is a comment inside a template area-->...</div>...@functions{...// This is a usual C# comment inside a code area...}
We can define comments in Razor files with the same syntax used in XML files. To define a comment, enclose the code between the <!--
and -->
symbols.
Inside a code block like the @functions
block, comments can be defined with the usual C# syntax.
String expressions in templates
The simplest way to define a Razor template is to write HTML that contains C# expressions to be evaluated inside HTML tags and attributes.
These C# expressions must be preceded by a @
symbol, as in the examples below:
<div class="@myDynamicCssClass"><p>Name: @customer.Name</p><p>Surname: @customer.Surname</p><p>Age: @((new DateTime(1,1,1)+(DateTime.Today-customer.DateOfBirth)).Year-1)<p></div>
When the expression is made just of field/property/method accessors, like myObj.Prop1.SubProp1
,
it is enough to place a @
immediately before the expression, like this: @myObj.Prop1.SubProp1
.
The whole expression must be enclosed in parentheses if the expression is more complex, such as when computing the customer age in the previous example.
In the previous customer example, both Name
and Surname
are strings, so the expression value can be immediately inserted in the surrounding HTML. The Razor engine needs ...