Razor Syntax Intro
Posted on March 6, 2025 (Last modified on May 26, 2025) • 2 min read • 404 wordsVideo is in Swedish
Razor is a powerful templating engine used in ASP.NET Core and ASP.NET MVC applications to separate presentation logic from application logic. It allows developers to create dynamic web pages with ease, making it an essential tool for building modern web applications.
In this article, we will introduce the basics of Razor syntax, covering its key features and components.
Razor syntax is based on C# and uses a combination of HTML and C# code. The syntax is designed to be easy to read and write, making it accessible to developers with varying levels of experience.
A basic Razor template consists of two parts: the HTML part and the C# part. The HTML part is used to define the structure of the page, while the C# part is used to add dynamic content.
Here’s an example of a simple Razor template:
@{
var name = "John Doe";
}
<html>
<body>
<h1>Welcome @name!</h1>
</body>
</html>
In this example, the @{ ... }
block is used to define a code block in C#. The var name = "John Doe";
statement declares a variable named name
and assigns it the value "John Doe"
. The @name!
syntax is used to inject the value of the name
variable into the HTML.
Razor provides several types of code blocks, including:
Razor provides several HTML helpers, including:
In this introduction to Razor syntax, we have covered the basics of using Razor templates in ASP.NET Core and ASP.NET MVC applications. We have seen how to define code blocks, use HTML helpers, and inject dynamic content into our templates.
With this knowledge, you are now ready to start building your own Razor-based web applications. Whether you’re a seasoned developer or just starting out, Razor provides a powerful toolset for creating dynamic and engaging user interfaces.
Swedish