AI Generate Razor docs instantly

Razor Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

3 snippets

Razor syntax fundamentals

Basic Razor View

@{
    ViewData["Title"] = "Home";
}

<h1>@ViewData["Title"]</h1>
<p>Welcome to our application!</p>

Inline Expression

<p>Hello, @User.Identity.Name!</p>
<p>Current time: @DateTime.Now.ToString("HH:mm:ss")</p>

Code Block

@{
    var greeting = "Hello";
    var name = "World";
    var message = $"{greeting}, {name}!";
}

<p>@message</p>

Directives

4 snippets

Razor directives and declarations

@model Directive

@model MyApp.Models.ProductViewModel

<h1>@Model.Product.Name</h1>
<p>@Model.Product.Description</p>

@using Directive

@using MyApp.Models
@using MyApp.Services
@using System.Linq

<p>@User.Identity.Name</p>

@inject Directive

@inject IConfiguration Configuration
@inject UserManager<ApplicationUser> UserManager

<p>API Key: @Configuration["ApiKey"]</p>

@functions Directive

@functions {
    public string GetGreeting(string name)
    {
        return $"Hello, {name}!";
    }

    public int Calculate(int a, int b)
    {
        return a + b;
    }
}

<p>@GetGreeting("User")</p>

Control Structures

4 snippets

Conditional and loop constructs

If-Else

@if (User.Identity.IsAuthenticated)
{
    <p>Welcome, @User.Identity.Name!</p>
    <a href="/logout">Logout</a>
}
else
{
    <a href="/login">Login</a>
}

Switch Expression

@{
    var statusBadge = Model.Status switch
    {
        "Active" => "badge-success",
        "Pending" => "badge-warning",
        "Inactive" => "badge-danger",
        _ => "badge-secondary"
    };
}

<span class="badge @statusBadge">@Model.Status</span>

Foreach

<table>
    <thead>
        <tr><th>Name</th><th>Price</th></tr>
    </thead>
    <tbody>
        @foreach (var product in Model.Products)
        {
            <tr>
                <td>@product.Name</td>
                <td>$@product.Price</td>
            </tr>
        }
    </tbody>
</table>

For Loop

<select>
    @for (int i = 1; i <= 10; i++)
    {
        <option value="@i">@i</option>
    }
</select>

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Layouts

2 snippets

Master page templates

Layout Declaration

@* _Layout.cshtml *@
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewData["Title"] - My App</title>
    @await RenderSectionAsync("Styles", required: false)
</head>
<body>
    <header>
        @await Html.PartialAsync("_Header")
    </header>
    <main>
        @RenderBody()
    </main>
    <footer>
        @await Html.PartialAsync("_Footer")
    </footer>
    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View with Layout

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewData["Title"] = "Products";
}

@section Styles {
    <link rel="stylesheet" href="~/css/products.css" />
}

<h1>Our Products</h1>
<!-- Content -->

@section Scripts {
    <script src="~/js/products.js"></script>
}

Partial Views

2 snippets

Reusable view fragments

Render Partial

@* Async (preferred) *@
@await Html.PartialAsync("_ProductCard", product)

@* Synchronous *@
@Html.Partial("_ProductCard", product)

Partial with Model

@* _ProductCard.cshtml *@
@model Product

<div class="product-card">
    <img src="@Model.ImageUrl" alt="@Model.Name" />
    <h3>@Model.Name</h3>
    <p>@Model.Description</p>
    <p class="price">$@Model.Price</p>
    <a href="/products/@Model.Id">View Details</a>
</div>

View Components

2 snippets

Complex reusable components

Invoke View Component

@await Component.InvokeAsync("ShoppingCart")

@await Component.InvokeAsync("ProductList", new { category = "Electronics" })

View Component Class

public class ShoppingCartViewComponent : ViewComponent
{
    private readonly ICartService _cartService;

    public ShoppingCartViewComponent(ICartService cartService)
    {
        _cartService = cartService;
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
        var cart = await _cartService.GetCartAsync(User.Identity.Name);
        return View(cart);
    }
}

Forms & Validation

2 snippets

HTML forms and model validation

Basic Form

@model ProductCreateViewModel

<form asp-action="Create" method="post">
    <div class="form-group">
        <label asp-for="Name"></label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>

    <div class="form-group">
        <label asp-for="Price"></label>
        <input asp-for="Price" class="form-control" />
        <span asp-validation-for="Price" class="text-danger"></span>
    </div>

    <button type="submit" class="btn btn-primary">Create</button>
</form>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Validation Summary

<div asp-validation-summary="All" class="text-danger"></div>

@* Or model errors only *@
<div asp-validation-summary="ModelOnly" class="text-danger"></div>

URL & HTML Helpers

3 snippets

Generating URLs and HTML

URL Helpers

<a href="@Url.Action("Index", "Home")">Home</a>
<a href="@Url.Action("Details", "Products", new { id = 1 })">Product</a>

<form action="@Url.Action("Create", "Products")" method="post">
    <!-- form content -->
</form>

Link Generation

@Html.ActionLink("Home", "Index", "Home")
@Html.ActionLink("Edit", "Edit", new { id = product.Id })

@Html.RouteLink("Product Details", "ProductDetails", new { id = product.Id })

Display Helpers

@Html.DisplayFor(m => m.Product.Name)
@Html.DisplayFor(m => m.Product.Price)
@Html.DisplayNameFor(m => m.Product.Category)

More Cheat Sheets

FAQ

Frequently asked questions

What is a Razor cheat sheet?

A Razor cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in Razor. It helps developers quickly look up syntax without searching through documentation.

How do I learn Razor quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important Razor concepts?

Key Razor concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my Razor code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your Razor code using AI.

Code Conversion Tools

Convert Razor to Other Languages

Easily translate your Razor code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate Razor Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week