Introduction to ASP.NET Razor: A Concise Syntax for Dynamic Web Pages

Learn about ASP.NET Razor, a powerful syntax for creating dynamic web pages by embedding server-side code (C#) directly within HTML. This introduction covers Razor syntax, key features, and provides simple examples to illustrate its use in generating dynamic web content.



Introduction to ASP.NET Razor

What is ASP.NET Razor?

ASP.NET Razor is a concise and expressive syntax for creating dynamic web pages. It allows you to embed server-side code (typically C#) directly within your HTML, simplifying the process of generating HTML content dynamically. The server processes the Razor code, generating the final HTML sent to the user's browser. Razor view files typically have a `.cshtml` extension.

The @ Symbol in Razor Syntax

The `@` symbol is used to denote Razor code within HTML. It indicates a transition from standard HTML markup to Razor syntax. The `@` symbol is used to begin:

  • Single-line expressions (e.g., `@variableName`)
  • Single-statement code blocks (e.g., `@ statement;`)
  • Multi-statement code blocks (e.g., `@{ ... }`)

Razor Keywords

Razor utilizes several keywords for specific functionalities within your views:

  • @functions: Defines helper functions within the view.
  • @inherits: Specifies a base class for the view.
  • @model: Specifies the model type for the view.
  • @section: Defines sections within the view (for layout management).
  • @helper: Defines helper functions (not supported in ASP.NET Core).

Example: Creating a Razor View

Let's create a simple Razor view that displays a name.

C# Controller Code (StudentsController.cs)

using System.Web.Mvc;
namespace RazorViewExample.Controllers
{
public class StudentsController : Controller
{
    public ActionResult Index() { return View(); }
}
}
Razor View Code (Index.cshtml)

@{
    Layout = null;
    var name = "Joseph";
}
<p>Index</p>
<p>My name is @name</p>
Output

(A screenshot showing the rendered output "Index My name is Joseph" would be included here.)