Razor Syntax
The Razor syntax is simple and intuitive, enabling developers to embed server-side logic into HTML pages. It uses the @
symbol to transition between server-side code and markup seamlessly.
Key Topics
Inline Code
Example
<p>The current year is @DateTime.Now.Year</p>
Explanation: Inline Razor code starts with @
and directly inserts the result of the server-side code into the HTML output.
Code Blocks
Example
@{
var greeting = DateTime.Now.Hour < 12 ? "Good Morning" : "Good Evening";
}
<p>@greeting! Welcome to our site.</p>
Explanation: Code blocks are enclosed in @{ }
. They allow you to execute multiple lines of server-side code before rendering the output.
Razor Directives
Example
@model MyApp.Models.User
<p>Hello, @Model.Name!</p>
Explanation: Razor directives, such as @model
, provide additional functionalities like specifying a strongly-typed model for the view.
Key Takeaways
- Razor syntax uses the
@
symbol to embed server-side code in HTML. - Inline code is for single expressions, while code blocks handle multiple statements.
- Directives enhance Razor's capabilities by adding features like model binding.