Skip to content

Views ​

Introduction ​

DotBlaze views come in two syntaxes, and one application can mix them:

  • Blade templates (.blade.html): Blade's {{ }}, @if … @endif, @foreach, @extends, @section, @yield, and @push, with C# expressions. The application template's layout and home page are Blade views.
  • Razor views (.cshtml) from ASP.NET Core MVC, described on this page. Layouts, sections, and partials are standard Razor.

Both compile with the application and share everything on this page: view locations, models, the helpers, and components. DotBlaze adds a base page class, DotBlazePage<TModel>, with Blade-style helpers such as @Route, @Csrf, @Method, @Old, and @Error.

Creating and Rendering Views ​

Return a view from a controller with View():

csharp
public class HomeController : BaseController
{
    public IActionResult Index() => View(model: Config.Get<string>("app.name"));
}
html
@* resources/views/home/Index.cshtml *@
@model string
@{
    ViewData["Title"] = "Home";
}
<h1 class="text-3xl font-bold">Welcome to @Model</h1>

Views are compiled with your application. After changing one, rebuild (or use dotnet watch).

View Locations ​

Views live in resources/views. A Blade view (Show.blade.html) is found at the same place as a Razor view with the same name (Show.cshtml). DotBlaze searches these locations, in order ({1} is the controller name without Controller, {0} the view name):

resources/views/{1}/{0}.cshtml       e.g. resources/views/post/Show.cshtml
resources/views/{0}.cshtml           e.g. resources/views/_Field.cshtml
resources/views/layouts/{0}.cshtml   e.g. resources/views/layouts/app.cshtml

View() without a name uses the action name, so PostController.Show renders resources/views/post/Show.cshtml. Pass a name to render another view of the same controller: View("Login").

The _ViewImports.cshtml file at the root of resources/views applies to every view below it and makes the DotBlaze helpers available:

html
@* resources/views/_ViewImports.cshtml *@
@using DotBlazeApp
@using DotBlaze
@inherits DotBlaze.DotBlazePage<TModel>
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Passing Data to Views ​

Pass a model to View(...) and declare its type with @model:

csharp
public async Task<IActionResult> Show(Post post)
{
    await post.Load(p => p.User);
    return View(post);
}
html
@model Post
<h1>@Model.Title</h1>
<p>by @Model.User?.Name</p>

For small extra values, use ViewData, as the views do for the page title. Razor HTML-encodes @ output by default.

Layouts ​

_ViewStart.cshtml sets the default layout for every Razor view (a Blade view chooses its layout with @extends):

html
@* resources/views/_ViewStart.cshtml *@
@{
    Layout = "app";
}

The name app resolves to resources/views/layouts/app.cshtml, or app.blade.html. The application template's layout is a Blade view that shows a Razor view's body with @yield('content') (see Blade layouts). Written in Razor, a layout renders the page with @RenderBody():

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>@ViewData["Title"] · @(Config.Get<string>("app.name"))</title>
    <link rel="stylesheet" href="~/build/app.css" asp-append-version="true" />
    <script defer src="~/build/alpine.js" asp-append-version="true"></script>
</head>
<body>
    <nav>
        @if (Auth.Check())
        {
            <span>@(Auth.User<User>()!.Name)</span>
            <form method="post" action="@Route("logout")">
                @Csrf()
                <button type="submit">Log out</button>
            </form>
        }
        else
        {
            <a href="@Route("login")">Log in</a>
        }
    </nav>
    <main>
        @RenderBody()
    </main>
</body>
</html>

Razor sections (@RenderSection / @section) work as usual. The CSS and Alpine.js build is described in frontend.

Partials ​

Use the <partial> tag helper (in a Blade view, @include). A partial name without a folder is found in resources/views. For example, a _Field partial for form fields, with a tuple as its model:

html
<partial name="_Field" model="@(("Email", "Email", "email", (string?)null))" />
html
@* resources/views/_Field.cshtml *@
@model (string Name, string Label, string Type, string? Value)
<label class="block">
    <span class="text-sm font-medium">@Model.Label</span>
    <input type="@Model.Type" name="@Model.Name"
           value="@(Model.Type == "password" ? "" : Old(Model.Name) ?? Model.Value)" />
    @if (Error(Model.Name) is string error)
    {
        <span class="text-sm text-red-600">@error</span>
    }
</label>

View Helpers ​

DotBlazePage<TModel> adds these members to every view:

HelperDescription
@Route(name, values)URL of a named route.
RouteIs(patterns)true if the current route's name matches any pattern (* is a wildcard), for active menu links: @class(("active", RouteIs("posts.*"))). See inspecting the current route.
@Csrf()Hidden CSRF token input. Required in every POST form with an action attribute; see CSRF protection.
@Method("PUT")Hidden _method input for method spoofing.
@Old(field, fallback)Flashed input after a failed validation, or the fallback.
@Error(field)First error message for a field, or null.
@Errors(field)All error messages for a field.
@HasErrors()true if any validation error was flashed.
await Can(ability, args), await Cannot(...)Gate check for the current user: @if (await Can("update", Model)) { ... }.

Field names in Old, Error, and Errors ignore case and underscores, so Error("first_name") finds an error for FirstName. Facades work in views as well, for example Auth.Check(), Auth.User<User>(), and Config.Get<string>("app.name"). Flash values set with .With(...) are read with TempData["key"] (see flash data).

Razor Syntax for Generic Calls ​

Razor treats < after an identifier as the start of an HTML tag. Wrap any generic method call in @( ... ):

html
<title>@(Config.Get<string>("app.name"))</title>     @* works *@
<title>@Config.Get<string>("app.name")</title>       @* does not compile *@

In plain C# code, such as an @{ ... } block or an @if (...) condition, generic calls need no extra parentheses. Markup inside a code block still needs them, as in <span>@(Auth.User<User>()!.Name)</span>.

Components ​

Components are Blade's <x-...> tags: reusable pieces of markup with attributes and slots. A component is a view in resources/views/components; <x-alert> renders components/alert (alert.blade.html or alert.cshtml), and <x-forms.input> renders components/forms/input. For example:

html
<x-alert type="success" dismissible>@status</x-alert>

The component view's model is a Component, with the tag's Attributes and the content between the tags, its Slot. In Razor (the sample app's components/alert.blade.html is the Blade version):

html
@model Component
@{
    var colors = Model.Attributes.Get("type", "success") == "error" ? "bg-red-100 text-red-800" : "bg-green-100 text-green-800";
}
<div attributes="@Model.Attributes.Except("type", "dismissible").Merge(new { @class = $"rounded p-3 {colors}", role = "alert" })">
    <span>@Model.Slot</span>
    @if (Model.Attributes.Has("dismissible")) { <button type="button" aria-label="Close">&times;</button> }
</div>

attributes="@..." writes the component's attributes on that element, like Blade's {{ $attributes }}. Merge adds defaults for attributes the tag did not give and combines class (<x-alert class="mt-4"> keeps both). Get(name, fallback), Has, Only, and Except pick attributes. Attribute values are strings; use @ expressions for dynamic values (<x-alert type="@level">). An attribute without a value (dismissible) is present with a null value.

Slots ​

Besides the default slot, a component can take named slots:

html
<x-card class="border-red-200">
    <x-slot:title>Delete account</x-slot:title>
    <p>Deleting your account also deletes your posts.</p>
</x-card>
html
@model Component
<section attributes="@Model.Attributes.Merge(new { @class = "rounded border bg-white p-6" })">
    @if (Model.HasSlot("title")) { <h2 class="text-lg font-semibold">@Model["title"]</h2> }
    @Model.Slot
</section>

<x-slot name="title"> works too. Model.SlotIsEmpty tells whether the default slot has content.

Enabling Components ​

Components are a tag helper; the application template enables it in resources/views/_ViewImports.cshtml:

html
@addTagHelper *, DotBlaze

It also renders live component tags (<live:counter />). Because it looks at every element, Razor's rule for tag helpers applies to every tag: C# directly inside a tag (<button @(disabled ? "disabled" : "")>) is not allowed. Write it as an attribute value instead: <button disabled="@disabled"> (as in plain Razor, false and null leave the attribute out and true writes disabled="disabled"). To exclude one element, prefix it with !: <!button ...>.

For components with C# logic of their own, ASP.NET Core's view components (<vc:name>) and tag helpers are available as usual.

Complete Example: Typed View ​

In the Blog template, add:

csharp
// app/Http/Controllers/GuideController.cs
using DotBlaze;
using Microsoft.AspNetCore.Mvc;

namespace Blog.Controllers;

public class GuideController : BaseController
{
    public IActionResult Show() =>
        View(model: new[] { "Install the template", "Run migrations", "Build a feature" });
}

Add Route.Get<Blog.Controllers.GuideController>("/guide", c => c.Show); inside Web.Map(). Create:

html
<!-- resources/views/guide/Show.blade.html -->
@model string[]
@extends('layouts.app')
@section('title', "Application guide")
@section('content')
    <h1>Application guide</h1>
    <ol>
        @foreach (var step in Model)
            <li>{{ step }}</li>
        @endforeach
    </ol>
@endsection

Run dotnet build and dotblaze serve; /guide shows the three steps inside the generated layout. The filename, controller name, action, and model type must agree. _ViewImports.cshtml and _ViewStart.cshtml remain Razor even when your page is Blade. The blog views extend this to forms, validation, authorization, and flash messages.