aspnet-mvc
  1. aspnet-mvc-razor-syntax

Razor Syntax - (ASP.NET MVC Views)

Razor is a markup syntax used to create views in ASP.NET MVC applications. It provides a concise way to generate HTML without getting in the way of writing code in C# or VB.NET. In this tutorial, we'll discuss the Razor syntax in ASP.NET MVC and how it can be used to create views.

Syntax

The syntax for Razor is similar to HTML, but with additional elements for inserting C# or VB.NET code. Razor code is enclosed in @{ ... } blocks. Razor expressions are enclosed in @(...), as shown below:

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    <h1>Welcome, @Model.Name</h1>
    <p>The time is now @DateTime.Now.ToString()</p>
</body>
</html>

Example

Here is an example of how to use Razor syntax in an ASP.NET MVC view:

@model MyApplication.Models.Person

<!DOCTYPE html>
<html>
<head>
    <title>Person Details</title>
</head>
<body>
    <h1>@Model.FullName</h1>
    <p>Email: @Model.Email</p>
    <p>Age: @Model.Age</p>
</body>
</html>

In this example, we are using Razor syntax to create an HTML view for a person object. We use the @model directive to specify the type of the model, and then use Razor expressions to display the model's properties.

Explanation

In Razor syntax, any text that is not enclosed in a @{ ... } block or @(...) expression is treated as HTML. Razor expressions are evaluated at runtime and output their results as HTML.

Razor also supports a variety of control structures, including if, foreach, for, and while, which can be used to dynamically generate HTML based on data in the model.

Use

Razor syntax is used in ASP.NET MVC to create views that display data from the model. It allows developers to create dynamic HTML pages using C# or VB.NET code.

Important Points

Here are some important points to keep in mind when using Razor syntax in ASP.NET MVC:

  • Razor expressions should be used sparingly in views, as they can quickly become hard to read and maintain.
  • Razor supports a variety of control structures, including if, foreach, for, and while, which can be used to generate dynamic HTML.
  • Razor syntax is not case-sensitive.

Summary

In this tutorial, we discussed Razor syntax in ASP.NET MVC for creating views. We covered the syntax, example, explanation, use, and important points of using Razor syntax in ASP.NET MVC. With this knowledge, you can use Razor syntax to create dynamic HTML pages that display data from the model in an MVC application.

Published on: