Skip to content

Live Components ​

Introduction ​

Live components are DotBlaze's version of Livewire: interactive components written in C# and Razor, without writing JavaScript. A component is a class whose public properties are its state and whose public methods are actions; its view renders that state. When the user clicks a button or types in a bound field, the browser sends the state and the action to the server, the server runs it and renders the view again, and the page is patched in place.

csharp
public class Counter : LiveComponent
{
    public int Count { get; set; }

    public void Increment() => Count++;
}
html
@model Counter
<div>
    <span>@Model.Count</span>
    <button type="button" live:click="Increment">+</button>
</div>

Everything travels over plain HTTP requests (no WebSocket, no server-side session per component): the state lives in a signed snapshot in the page.

Installation ​

Live components are part of the DotBlaze package. Add the script to your layout's <head>, before Alpine:

html
<head>
    ...
    @Live.Scripts()
    <script defer src="~/build/alpine.js" asp-append-version="true"></script>
</head>

@Live.Scripts() outputs a CSRF token, a small style rule, and /_live/live.js (DotBlaze's client, navigation, and morphdom), served by the framework; there is nothing to install with npm. The application template's layout already includes it.

Creating Components ​

shell
dotblaze make:live Counter

This creates app/Live/Counter.cs (namespace YourApp.LiveComponents) and a Blade view, resources/views/live/counter.blade.html, and adds the namespace to _ViewImports.cshtml. A component's name is its class name in kebab case (PostSearch → post-search), and its view is resources/views/live/{name}.blade.html (or {name}.cshtml for a Razor view) with the component as @model. Override View to use another view. Component classes must have unique names in the application.

NOTE

The namespace is LiveComponents, not Live: a namespace called Live would hide the Live facade.

The view must have one root element; DotBlaze adds its attributes to it.

Rendering Components ​

html
<live:counter />
<live:counter step="2" key="first" />
<live:post-stats lazy />

The tag's name is the component's name (its class name in kebab case); its attributes set public properties before Mount() (step sets Step, step-size sets StepSize), except key, lazy, and live:model (a parent binding). The tags need the component tag helper (@addTagHelper *, DotBlaze, in the template's _ViewImports.cshtml). Attribute values are strings, converted to the property's type. To pass objects, use the C# form:

html
@(await Live.Render<Counter>())
@(await Live.Render("counter"))

Generic calls in Razor markup need the parentheses (see views).

Passing Parameters ​

Parameters set public properties before Mount():

html
@(await Live.Render<Counter>(new { Count = 10, Step = 2 }))

Properties ​

Public properties with a public getter and setter are the component's state. They are serialized to JSON after every request and restored before the next one, so their types must be JSON-serializable. Models are stored by their key and fetched again on every request, like in queued jobs.

Locked Properties ​

The browser can change any public property (that is what live:model does). Mark properties it must not change with [Locked]; an update to one is refused with 403. Properties holding models (or lists of models) are always locked, so the browser cannot swap a model id:

csharp
[Locked] public long PostId { get; set; }
public Post Post { get; set; } = null!;   // locked automatically

Computed Values ​

Use Computed(() => ...) inside a getter to memoize a value for the current component request. The caller's member name is the default cache key. Computed values are not public writable state, so they are not sent in the snapshot or directly writable through live:model.

csharp
public int Quantity { get; set; } = 1;
public decimal Price { get; set; } = 25_000;
public decimal Total => Computed(() => Quantity * Price);

public void AddItem()
{
    Quantity++;
    ForgetComputed(nameof(Total));
}

Repeated reads of Total in the same request evaluate the factory once, including when the result is null. A new HTTP update creates a new component instance and a fresh cache. ForgetComputed("Total", "Other") invalidates named entries; ForgetComputed() clears all entries. Invalidation is explicit: changing a dependency does not automatically invalidate a cached value. Invalidate in the action or UpdatedQuantity() hook when a value may already have been read during the request. You may pass key: "custom-key"; use a distinct key for each computation and result type.

Async computations cache their Task, so multiple callers share the same query:

csharp
public Task<int> PostCount => Computed(() => Post.Query().Count());

public async Task DeletePost(long id)
{
    var post = await Post.FindOrFail(id);
    await Gate.Authorize("delete", post);
    await post.Delete();
    ForgetComputed(nameof(PostCount));
}
html
<p>Posts: @(await Model.PostCount)</p>

A failed or canceled cached Task is retried on the next computed read. Use Task<T> for async factories, not ValueTask<T> (which may not support repeated consumption). This is a C# helper, not an attribute that intercepts arbitrary getters. It does not persist across requests or share results between users; use the normal Cache facade with explicitly authorized, correctly scoped keys if persistent caching is wanted.

Values that only need calculating once before a render can also use properties with a private setter, filled in Rendering(). From the sample's PostSearch:

csharp
public string Search { get; set; } = "";
public int Page { get; set; } = 1;

public Paginator<Post> Results { get; private set; } = null!;

public override async Task Rendering()
{
    var term = Search.Trim();
    Results = await Post.Scope(Post.Latest)
        .Where(p => term == "" || p.Title.Contains(term) || p.Body.Contains(term))
        .With(p => p.User)
        .Paginate(10, Page);
}

URL State ​

Mark string, boolean, or numeric properties (including nullable ones) with [Url] to initialize them from the query string and keep the URL in sync after updates:

csharp
[Url("search", History = true)] public string Search { get; set; } = "";
[Url("page", History = true)] public int Page { get; set; } = 1;

?search=hello&page=2 loads those values before Mount(). The name defaults to the property name; give each URL-bound property on the page a unique query name. Values equal to their initial defaults are omitted. Other query parameters and the URL fragment are preserved.

By default changes replace the current history entry. History = true pushes an entry, so Back/Forward restore the component's properties and re-render it. Locked and reactive properties cannot be URL-bound.

Actions ​

Calling Actions ​

Public methods are actions. They may be async and take parameters:

csharp
public void GoToPage(int page) => Page = Math.Max(1, page);

public async Task Delete(long id)
{
    var post = await Post.FindOrFail(id);
    await Gate.Authorize("delete", post);
    await post.Delete();
}
html
<button type="button" live:click="GoToPage(@(Model.Page + 1))">Older</button>
<button type="button" live:click="Delete(@post.Id)">Delete</button>
<form live:submit="Save">...</form>
<input live:keydown.enter="Search" />
DirectiveFires on
live:clickclick (.prevent, .stop, .self modifiers)
live:dblclickdouble click
live:submitform submit (the default submit is always prevented; the form's buttons are disabled until the response)
live:keydownkey press; .enter, .escape, .tab, .space, arrows, or a key name

Arguments are JavaScript expressions evaluated in the browser ($event is the DOM event) and converted to the parameter types on the server.

Magic Actions ​

ActionEffect
$refreshRe-render without calling anything.
$set('Name', value)Set a property and re-render.
$toggle('Name')Flip a boolean property.
$dispatch('event', data)Dispatch an event from the browser.

Security ​

Treat every action like a controller action: anyone can call it with any arguments. Authorize inside the action (Gate.Authorize, see authorization); an AuthorizationException answers 403, a missing model 404. Only public methods declared on your component are callable: lifecycle hooks, Updating*/Updated* hooks, and the base class's members (Redirect, Dispatch, ...) are not. Each request must carry the CSRF token, and a snapshot that was changed in the browser is refused with 403.

Persistent Middleware ​

Updates are sent to /_live/update, not to the page's route, yet they still pass the page's checks: when a component is rendered, the route's middleware (with its parameters) and its passed .Can(...) checks are stored in the signed snapshot, and every update runs them again before the component is restored. Like Livewire's persistent middleware, but every alias is persistent by default.

csharp
Route.Get<ReportController>("/reports", c => c.Index).Middleware("auth", "verified", "role:admin");
Route.Get<PostController>("/posts/{post}/edit", c => c.Edit).Can("update", "post");

A component on these pages stops working as soon as the user's email is no longer verified, the admin role is taken away, or the post's policy no longer allows update:

  • The middleware runs as if the page itself were requested again: a GET of the page's path, with its query string and route values, asking for HTML. A middleware that redirects (as verified does, or auth for a guest) makes the browser go there, the same as Redirect from an action.
  • Any other refusal (a 403 from role) is answered with that status, and the browser fires a live:error event; the component keeps its state.
  • .Can checks fetch their models again by key and ask the Gate again; a refusal answers 403.

guest, signed (a signed link may already have expired), csrf (updates check the token themselves), and trim-strings are not run again. throttle is, so live updates count toward the page's limit. To skip another middleware, for example one that counts requests, call this in a provider's Boot method:

csharp
Live.SkipPersistentMiddleware("throttle");

Components rendered during an update (new children) keep the checks of the page they are on. A component rendered outside a route (in a mail view, for example) has nothing to check. A logged-out user does not reach these checks at all: the CSRF token belongs to the login, so the update is refused with 419 and the browser offers to reload the page.

NOTE

These checks guard the page, not each action. Keep authorizing actions that change data (Gate.Authorize), since an action may need more than the page did.

Data Binding (live:model) ​

live:model binds an input to a property. The input's value is set from the state after every render.

html
<input type="text" live:model="Title" />                      <!-- sent with the next action -->
<input type="search" live:model.live="Search" />              <!-- sent while typing (150 ms debounce) -->
<input type="search" live:model.live.debounce.300ms="Search" />
<input type="text" live:model.blur="Title" />                 <!-- sent when the field loses focus -->
<select live:model.change="Sort">...</select>                 <!-- sent on change -->
<input type="checkbox" live:model="Published" />              <!-- bool -->

Like Livewire 3, plain live:model is deferred: the value is kept in the browser and sent with the next action, so typing costs no requests. Numbers typed into inputs arrive as strings and are converted to the property type; a value that cannot be converted adds a validation error to that property instead of failing the request.

Property paths can address initialized DTOs, lists/arrays, and dictionaries with string keys:

html
<input live:model="Form.Title" />
<input live:model="Items.0.Name" />
<input live:model="Preferences.Theme" />

DTO properties need public getters and setters. List indexes must exist; intermediate objects cannot be null. Nested [Locked] properties and model references remain protected, including when an entire containing object is replaced. The general Updating/Updated hooks receive the full path; the property's UpdatingForm/UpdatedForm hooks receive the updated root value if they take a parameter.

Several checkboxes can bind to a list or array; their value attributes become the selected values. A checkbox bound to a boolean continues to use true/false:

csharp
public List<string> Roles { get; set; } = [];
html
<input type="checkbox" value="editor" live:model="Roles" /> Editor
<input type="checkbox" value="author" live:model="Roles" /> Author

Forms and Validation ​

Derive from LiveComponent<TSelf> to get FluentValidation rules, written like a form request:

csharp
public class PostForm : LiveComponent<PostForm>
{
    public string Title { get; set; } = "";
    public string Body { get; set; } = "";

    public override void Rules(RuleSet<PostForm> r)
    {
        r.Field(x => x.Title).NotEmpty().MaximumLength(255);
        r.Field(x => x.Body).NotEmpty();
    }

    public async Task Save()
    {
        await Validate();   // invalid → errors are shown and Save stops here
        ...
    }
}

Validate() stops the action with the errors when the data is invalid; the component is rendered with them. In the view:

html
<input type="text" live:model.blur="Title" />
@if (Model.Error("Title") is string error) { <span class="text-red-600">@error</span> }

Error(field), HasError(field), HasErrors(), Errors, AddError(field, message), and ResetErrors(fields...) manage the error bag, which is kept between requests.

Real-Time Validation ​

Validate one field when it changes with an Updated{Property} hook and ValidateOnly:

csharp
public Task UpdatedTitle() => ValidateOnly(nameof(Title));

Without JavaScript ​

A live form can also be an ordinary form: give the inputs name attributes, an action, and @Csrf(). With JavaScript, live:submit takes over; without it, the browser posts to your controller. The sample's post-form.cshtml does this, showing Model.Error(...) ?? Error(...) so both the component's errors and flashed validation errors appear.

File Uploads ​

Bind a file input to a LiveFile property (List<LiveFile> for multiple):

csharp
public LiveFile? Cover { get; set; }

public override void Rules(RuleSet<PostForm> r) =>
    r.Field(x => x.Cover)
        .Must(f => f is null || f.IsImage).WithMessage("The cover must be an image.")
        .Must(f => f is null || f.Size <= 2 * 1024 * 1024).WithMessage("The cover may not be larger than 2 MB.");

public Task UpdatedCover() => ValidateOnly(nameof(Cover));

public async Task Save()
{
    await Validate();
    if (Cover is not null) post.CoverPath = await Cover.Store("covers", "public");
}
html
<input type="file" accept="image/*" live:model="Cover" />
<span live:loading live:target="Cover">Uploading…</span>

When a file is chosen it is uploaded at once to /_live/upload and kept in storage/app/live-tmp; the property holds a signed, expiring reference (24 hours) to it. Name, Size, ContentType, Extension, IsImage, and OpenRead() describe it; Store(directory, disk) and StoreAs(directory, name, disk) move it to a disk. ContentType and Extension describe client-supplied metadata, not verified content. IsImage checks file signatures for PNG, JPEG, GIF, and WebP; it rejects SVG/HTML and does not fully decode images or scan for malware. Store assigns detected raster images a matching extension (.png, .jpg, .gif, or .webp) regardless of the supplied name; other files keep only a short alphanumeric extension. StoreAs uses the explicit name you supply, so do not use an untrusted name or serve arbitrary uploads inline from the application's origin. Uploads larger than live.upload_max_kb (default 12288) are refused with 413, and the browser fires a live:upload-error window event. An upload carries its component's signed snapshot, and passes the page's persistent middleware like any update; an upload without one is refused.

Cover.TemporaryUrl() returns a signed preview URL that expires with the upload. The preview endpoint checks the file's bytes and serves PNG, JPEG, GIF, and WebP only; SVG/HTML and invalid tokens are refused. Treat the URL as a temporary bearer link. Storing the upload removes the temporary file and invalidates its preview.

Upload events bubble from the file input to window: live:upload-start, live:upload-progress (detail.progress, 0–100), live:upload-finish, live:upload-cancel, and live:upload-error (detail.message). Every event includes detail.name and detail.component.

html
<div x-data="{ progress: 0 }" x-on:live:upload-progress="progress = $event.detail.progress">
    <input type="file" live:model="Cover" />
    <progress max="100" x-bind:value="progress"></progress>
    <button type="button" x-on:click="$live.$cancelUpload('Cover')">Cancel upload</button>
</div>

From ordinary JavaScript use Live.find(id).cancelUpload("Cover"). Cancellation leaves the previous property value intact. Selecting another file for the same property cancels the previous transfer; any temporary file already received by the server is cleaned up by the normal expiry cleanup.

File Downloads ​

Call Download(bytes, name, contentType) inside an authorized action. The browser receives the file as an effect, creates a Blob download, and releases its temporary object URL. The component can render and update its snapshot normally in the same response.

csharp
public async Task Export()
{
    await Gate.Authorize("export-posts"); // define the ability for your application
    var bytes = System.Text.Encoding.UTF8.GetBytes("title,count\nPublished,12\n");
    Download(bytes, "posts.csv", "text/csv; charset=utf-8");
}
html
<button type="button" live:click="Export">Download CSV</button>

The MIME type defaults to application/octet-stream. Use a file name, not a path. Only one download is sent per update (the last Download call wins). Files are base64 encoded in the response, so the limit is 10 MiB before encoding. For large files or range requests, use a normal authenticated download endpoint instead. Do not load a server file path directly from unvalidated browser input. Download content is not included in the signed component snapshot. Browser download policies may still apply.

Scoped Styles ​

Override Styles with CSS. DotBlaze inserts a style block inside the component root, wrapped in a native CSS @scope tied to this component instance's live:id.

csharp
public override string Styles => """
    :scope { border: 1px solid #888; padding: 1rem; }
    .heading { font-weight: bold; }
    button:hover { text-decoration: underline; }
    @media (prefers-reduced-motion: no-preference) {
        button { transition: opacity 150ms; }
    }
    """;

Use :scope for the component root. Ordinary selectors target its descendants and stop at nested Live component roots. Two component instances have separate scopes, and replacing/removing the root also removes its style block. Normal CSS inheritance still applies: inherited color or font values can reach children. This is selector scoping, not Shadow DOM or a security sandbox; CSS names such as keyframes are not automatically renamed. Supply developer-authored CSS only, not user input.

Native CSS @scope support is required; unsupported browsers ignore the scoped rules. Keep global styles in your regular stylesheet. Teleported content is physically outside the component root, so these scoped selectors do not reach it: give teleported content explicit classes and style those in the page stylesheet.

Streaming Content (live:stream) ​

A long action can send incremental output before its final render:

csharp
public async Task RunReport()
{
    await Gate.Authorize("run-reports");
    await Stream("progress", "Starting…\n", replace: true);
    // Perform the work here, awaiting each operation.
    await Stream("progress", "Finished.\n");
}
html
<div>
    <button type="button" live:click="RunReport">Run report</button>
    <pre live:stream="progress" aria-live="polite"></pre>
</div>

await Stream(target, content, replace: false, html: false) appends text by default; replace: true clears previous content first. Alternatively, live:stream.replace="progress" makes that target replace its content on every chunk. Streamed target contents are preserved through the action's final HTML morph; keep the target present in the returned view. Only opt into html: true for trusted, server-authored HTML. Target names are scoped to the current component. Always await each call; do not launch fire-and-forget producers after the action has returned.

Streaming uses the normal authenticated/CSRF-checked update endpoint with an NDJSON response. Snapshot verification and the page's persistent middleware run before the action. The final frame carries the ordinary HTML, signed snapshot, and effects. A failed action sends an error frame without a successful new snapshot; previously displayed chunks cannot be rolled back, and the action is not automatically retried. Once bytes have been flushed, the HTTP status cannot change, so failures are conveyed in that frame. Proxies may buffer responses despite the no-buffer header.

Components with a live:stream target are sent independently rather than bundled with other component updates. Non-streaming clients and batch updates receive accumulated frames in effects.streams at completion instead of incremental delivery. Streaming is not a background job: the HTTP request must stay open, and application code should honor request cancellation during long work. Complete login/logout, cookie changes, and other response-header operations before the first chunk; headers are already committed after it. In particular, cookie-backed session changes cannot be persisted by setting a new cookie after streaming has started.

HTML Directive Reference ​

DotBlaze uses live:, not wire:. The table covers every directive in the feature checklist plus DotBlaze's supporting directives. Matching names do not promise every modifier or internal behavior of a particular Livewire release: use the syntax documented on this page.

DirectivePurposeDetails
live:bindBind an HTML attribute to a client-side state expressionClient bindings
live:click, live:dblclickCall a server actionActions
live:submitSubmit to an action without ordinary form navigationActions
live:keydownCall an action for a keyActions
live:modelTwo-way form bindingData binding
live:loadingShow or change an element while a request runsLoading states
live:targetLimit loading/dirty behavior to actions or propertiesLoading states
live:navigateSame-origin client navigationPage navigation
live:currentApply classes to the active navigation linkCurrent links
live:cloakHide until the component initializesAdd the attribute to an element; Live.Scripts() supplies the hiding CSS
live:dirtyIndicate unsaved local editsDirty state
live:confirmAsk before executing an actionConfirmation
live:transitionAnimate show/hide and DOM appearance/removalTransitions
live:initCall an action once when an element is initializedInitialization
live:intersectCall an action when an element enters/leaves the viewportIntersection
live:pollPeriodically call an action or refreshPolling
live:offlineIndicate the browser's offline stateOffline
live:ignorePreserve DOM managed by another libraryIgnoring updates
live:refName an element for component-scoped JavaScript accessReferences
live:replaceReplace markup rather than morphing itReplacing DOM
live:showToggle display from a state expressionClient bindings
live:sortReorder items with pointer or keyboard inputSorting
live:streamReceive incremental server outputStreaming
live:textSet text content from a state expressionClient bindings
live:teleportRender template contents in another DOM locationTeleport
live:keyGive a repeated element stable identityKeys

live:id, live:snapshot, live:checksum, live:props, and live:lazy are framework-managed transport/lifecycle attributes. Do not handcraft signed snapshots or mutate these attributes to bypass the server's component checks.

Lifecycle Hooks ​

HookRuns
Boot()At the start of every request, including the first render.
Mount()Once, on the first render, after the parameters are set.
Hydrate()At the start of every later request, after the state is restored.
Updating(property, value) / Updating{Property}(value)Before a property is changed from the browser.
Updated(property) / Updated{Property}()After it is changed.
Rendering()Before every render.
Dehydrate()At the end of every request, before the state is saved.

All hooks may be async. Updated{Property} and Updating{Property} are found by name and may take the new value as a parameter.

Events ​

Dispatch(name, data) sends an event to every component on the page that listens to it with [On(name)], and fires a window event with that name (listen with Alpine's x-on:name.window). From the sample, marking notifications as read refreshes the bell in the navigation:

csharp
public class NotificationList : LiveComponent
{
    public async Task MarkAllRead()
    {
        await Auth.User<User>()!.MarkNotificationsAsRead();
        Dispatch("notifications-read");
    }
}

public class NotificationBell : LiveComponent
{
    [On("notifications-read")]
    [On("notification-received")]
    public void Refresh() { }
}

A listener method may take the event data as a parameter. DispatchTo<T>(name, data) reaches only components of type T; DispatchSelf(name, data) only this one. From JavaScript, Live.dispatch(name, data) does the same, and Live.dispatch(name, data, "order-status") reaches only components with that name ("@" + id for a single instance). That is how components react to broadcasts.

Listening for Broadcasts ​

A component reacts to a broadcast event in two parts: the Echo client in the browser receives the event and forwards it with Live.dispatch, and the component listens with [On]. Each event the component receives is an ordinary request to the server, so the listener can query the database and the component renders again.

1. Broadcast an event (see defining broadcast events). From the sample app:

csharp
public sealed record PostCreated(Post Post) : IShouldBroadcastNow
{
    public IEnumerable<Channel> BroadcastOn() => [new Channel("posts")];

    public object BroadcastWith() => new { id = Post.Id, title = Post.Title, author = Post.User?.Name };
}
csharp
await Event.Dispatch(new PostCreated(post));

Private and presence channels also need an authorization callback in routes/channels.cs; public channels do not.

2. Forward it to components. Create the Echo client once in the layout, after @Live.Scripts(), and dispatch each event the whole application cares about:

html
<script src="~/build/signalr.js"></script>
@Broadcast.Scripts()
<script>
    if (!window.Echo) {
        window.Echo = new DotBlazeEcho();
        Echo.notification(n => Live.dispatch("notification-received", n));
        Echo.channel("posts").listen("PostCreated", e => Live.dispatch("post-created", e));
    }
</script>

The if matters with page navigation, which runs the new page's inline scripts again: without it every navigation would open another connection and add the listeners twice.

3. Listen in the component. An empty method is enough to render again with fresh data, as the sample's post list does:

csharp
public class PostSearch : LiveComponent
{
    [On("post-created")]
    public void Refresh() { }
}

To use the event's data, take it as a parameter. The broadcast JSON is read into the parameter's type, and property names ignore case:

csharp
public sealed record PostCreatedData(long Id, string Title, string? Author);

[On("post-created")]
public void Added(PostCreatedData post) => LatestTitle = post.Title;

Channels That Depend on the Page ​

When the channel name holds an id, such as a private channel for one order, subscribe from the page's view and push the script to the layout's @stack('scripts'). Pass the component's name as the third argument so only that component receives the event:

html
{{-- orders/Show.blade.html --}}
@model Order
@extends('layouts.app')

@section('content')
    {{ await Live.Render<OrderStatus>(new { Order = Model }) }}
@endsection

@push('scripts')
<script>
    Echo.private("orders.{{ Model.Id }}")
        .listen("OrderShipped", e => Live.dispatch("order-shipped", e, "order-status"))
        .error(e => console.warn("Not allowed to listen to this order.", e));

    // With page navigation, leave the channel when the page is left.
    document.addEventListener("live:navigating", () => Echo.leave("orders.{{ Model.Id }}"), { once: true });
</script>
@endpush
csharp
public class OrderStatus : LiveComponent
{
    public Order Order { get; set; } = null!;

    [On("order-shipped")]
    public Task Refresh() => Order.Refresh();
}
csharp
// routes/channels.cs
Broadcast.Channel("orders.{order}", (User user, Order order) => user.Id == order.UserId);

Keep these scripts in the layout or the page view, not in the component's own view: a component's markup is updated in place when it renders again, and scripts inside it do not run then, nor when a lazy component loads.

Echo.leave(name) removes the channel and its listeners. Subscribing to a channel that is already open reuses it, so calling .listen again for the same event without leaving first adds a second listener.

Leaving Out the Sender ​

When an action in a component broadcasts an event, the browser that ran the action usually already shows the change. Broadcast with ToOthers() to skip it: live component requests send the X-Socket-ID header automatically once Echo is connected.

csharp
public async Task Save()
{
    var comment = await Comment.Create(new { Body, PostId });
    await Broadcast.Send(new CommentPosted(comment)).ToOthers();
}

Loading States ​

Elements with live:loading are hidden and shown only while the component is waiting for the server:

html
<span live:loading>Saving…</span>
<span live:loading.remove>Save</span>                        <!-- hidden while loading -->
<div live:loading.class="opacity-50">...</div>
<div live:loading.class.remove="bg-white">...</div>
<button live:loading.attr="disabled">Save</button>
<span live:loading.flex>...</span>                           <!-- shown as display: flex -->
<span live:loading live:target="Save,Cover">...</span>       <!-- only for these actions or properties -->

Dirty, Offline, and Confirmation ​

live:dirty shows an element while local state differs from the accepted server state. live:target limits it to specific properties (including nested paths). live:offline shows an element while the browser reports it is offline. Both support .remove, .class, .class.remove, and .attr:

html
<span live:dirty live:target="Form.Title">Unsaved changes</span>
<button live:dirty.attr="disabled">Available when clean</button>
<span live:offline>Connection lost</span>
<button live:click="Delete(7)" live:confirm="Delete this post?">Delete</button>

live:confirm uses the browser's confirmation dialog before an action. Cancel prevents the action and the element's default behavior. Offline detection uses navigator.onLine; a server error still raises live:error. Failed updates retain local changes for the next explicit attempt; actions are not automatically retried.

Polling ​

html
<div live:poll>...</div>                       <!-- $refresh every 2 seconds -->
<div live:poll.15s>...</div>
<div live:poll.5s="CheckStatus">...</div>     <!-- call an action -->
<div live:poll.10s.keep-alive>...</div>       <!-- also while the tab is in the background -->

Polling pauses while the browser tab is hidden. The sample's notification bell polls every 15 seconds.

Lazy Loading ​

A slow component can render a placeholder first and load when that placeholder enters the viewport:

html
@(await Live.Render<PostStats>(lazy: true))
csharp
public class PostStats : LiveComponent
{
    public int Posts { get; set; }

    public override async Task Mount() => Posts = await Post.Query().Count();

    public override string Placeholder() => "<p>Loading stats…</p>";
}

Mount() runs in the follow-up request, not during the page render. The placeholder must have one root element. Give it enough size for the browser to observe it. Each lazy component loads once; removing it before it is visible cancels observation.

Nesting Components ​

A component's view can render other components. When the parent re-renders, children that are already on the page keep their state: the server sends a placeholder for them, and the browser leaves them alone. Children are matched by key, by default their position; give a key when the list can change order:

html
@for (var i = 1; i <= Model.Counters; i++)
{
    @(await Live.Render<Counter>(new { Step = i }, key: "counter-" + i))
}

Ordinary parameters reach a child only when it is first rendered. Use a reactive property or dispatch an event for later parent changes.

Reactive and Modelable Properties ​

Mark child properties with [Reactive] to accept subsequent parent values:

csharp
public class Results : LiveComponent
{
    [Reactive] public string Search { get; set; } = "";
}
html
@(await Live.Render<Results>(new { Search = Model.Search }, key: "results"))

After the parent renders, a changed value triggers a child update. Parent-to-child updates are signed for that child; direct browser writes to [Reactive] properties are refused.

For a two-way input component, mark exactly one writable child property with [Modelable]:

csharp
public class Picker : LiveComponent
{
    [Modelable] public string Value { get; set; } = "";
}
html
<!-- Parent view: Selected is a writable parent property. -->
<live:picker key="picker" live:model="Selected" />
<!-- Equivalent C# rendering: -->
@(await Live.Render<Picker>(key: "picker", model: "Selected"))
<!-- Inside Picker's view: -->
<input live:model.live="Value" />

Parent changes update the child, and accepted child changes update and commit the parent. This uses normal component requests, validation, and hooks. A modelable property cannot also be locked or reactive.

Keys in Lists ​

Give repeated HTML elements stable, unique live:key values so reordering preserves the correct DOM node and widget state:

html
@foreach (var item in Model.Items)
{
    <div live:key="item-@item.Id">@item.Name</div>
}

Keys should identify records, not their current indexes, and be unique within their owning component. Child component roots are matched by live:id; other elements use live:key, falling back to the HTML id. Continue passing key to Live.Render or <live:...> for nested components.

Redirecting and Flash Data ​

csharp
Flash("status", "Post created.");
RedirectRoute("posts.show", new { post = post.Id });   // or Redirect("/posts")

The browser navigates after the response. Flash stores flash data for the next page. SkipRender() updates the state without sending new HTML.

Add live:navigate to same-origin links to fetch and display the next page without reloading the JavaScript runtime:

html
<a href="/posts" live:navigate>Posts</a>

Live.navigate("/posts") does the same from JavaScript. Both pages need @Live.Scripts(). Navigation updates the title, head, body, CSRF token, and browser history. Back/Forward between pages fetches the destination again. Components, timers, uploads, and Alpine state on the previous page are cleaned up.

External scripts already loaded are reused; new external scripts and the destination's inline scripts run. Put one-time application initialization in an external script, and release page-specific global listeners or connections on live:navigating. live:navigating is a cancelable document event; live:navigated fires after the new page initializes. Both expose detail.url. Modifier-clicks, downloads, and links targeting another window retain normal browser behavior. External destinations, incompatible runtime versions, or failed HTML fetches use a normal page navigation.

Ignoring DOM Updates (live:ignore) ​

Use live:ignore around DOM managed by a JavaScript widget (such as a rich-text editor or a custom select). Like Livewire's wire:ignore, it keeps the element's attributes and all its contents intact when the component's HTML is patched:

html
<div live:ignore>
    <div id="editor"></div>
</div>

Use live:ignore.self to preserve only the element's own attributes (for example, a modal's client-managed class or style), while letting its children update normally:

html
<div live:ignore.self class="modal">
    <span>@Model.Count</span>
</div>

Both directives work on the component's root too. They only control HTML morphing: event handlers and explicit directives such as live:model and live:loading still work. An ignored element can still be removed if it is no longer rendered by the server.

Client Bindings (live:bind, live:text, live:show) ​

These directives evaluate JavaScript expressions against the component's client state, including pending local edits, without a server round trip. Use property names directly, or $live.Name. Client expressions cannot read a server-only computed getter; render computed values in Razor or expose an appropriate ordinary state value.

html
<div>
    <input live:model="Name" />
    <span live:text="Name + ' — ' + Count + ' items'"></span>
    <section live:show="Open">Details</section>
    <button live:bind:disabled="Busy" live:bind:title="Name">Save</button>
    <button live:bind="({ title: Name, disabled: Busy })">Another button</button>
</div>
  • live:text sets textContent, not HTML. It replaces the element's contents; do not place child components inside it.
  • live:show toggles display while keeping the element in the DOM. Pair it with live:cloak to avoid a flash before initialization, and live:transition to animate changes.
  • live:bind:attribute binds one attribute; live:bind accepts an object of attribute/value pairs. false or null removes an attribute; true writes an empty boolean attribute. Write expressions and attribute names as trusted application code. Executable bindings such as inline event attributes and unsafe URL schemes are refused. Use live:text rather than inserting HTML from user input.

Like action argument expressions, these expressions are evaluated with JavaScript's Function constructor in the browser. They require a CSP that permits this evaluation; a strict CSP without unsafe-eval is not supported by this runtime. Never construct expressions from untrusted input. They are not authorization or validation: enforce both again on the server. Avoid mixing competing bindings on the same attribute/element, such as live:show and Alpine x-show controlling the same display style.

Initialization and Intersection ​

live:init calls an action once when that DOM element is initialized. Unlike Mount(), which runs before initial server rendering, this action runs in a follow-up browser request:

html
<div live:init="LoadSummary">
    <span live:loading live:target="LoadSummary">Loading summary…</span>
</div>

An existing morphed element does not run init again; a genuinely replaced/new element does. Make initialization actions safe to repeat, since a page reload creates new elements. The directive is distinct from the document event named live:init, which announces that the JavaScript runtime is ready.

live:intersect runs an action when the element crosses a viewport threshold:

html
<div live:intersect.once="LoadMore">Load the next page when visible</div>
<div live:intersect.half="TrackVisible">At least half visible</div>
<div live:intersect.full="TrackFullyVisible">Entirely visible</div>
<div live:intersect.leave="PausePreview">Leaving the viewport</div>
ModifierMeaning
.enterEntering the threshold; default
.leaveLeaving the threshold, only after having entered
.onceStop observing after the matching event fires once
.halfIntersection threshold 0.5
.fullIntersection threshold 1

Without .half/.full, entering means any intersection. Elements need nonzero dimensions. Observers are removed when their elements/components are removed or the page navigates away. This is a general action trigger; lazy loading remains the way to defer constructing a whole component.

Apply classes to navigation links matching the current URL. This directive also works outside Live components:

html
<a href="/posts" live:navigate live:current="font-bold underline">Posts</a>
<a href="/posts" live:navigate live:current.exact="font-bold">Posts index only</a>
<a href="/" live:navigate live:current>Home</a>

The default class is active. Default matching uses pathname segments: /posts matches /posts/7, but not /postscript. .exact requires the same pathname. / only matches the root path. Query strings and fragments do not affect matching. Classes are refreshed after Live navigation and history changes; choose classes dedicated to the active state.

Transitions (live:transition) ​

Animate show/hide or elements entering/leaving a morphed view:

html
<section live:show="Open" live:transition>Animated panel</section>
<p live:show="Saved" live:transition.opacity.300ms>Saved</p>

The default transition is a 150 ms fade and scale. .opacity uses fading only, .in limits animation to entering, .out limits it to leaving, and a duration such as .300ms or .1s overrides the default. The runtime respects prefers-reduced-motion. Use stable keys for repeated items; transitions do not replace identity tracking. This is a built-in animation, not the full Alpine class-based transition API. Avoid two animation systems controlling the same element.

Element References (live:ref) ​

Name an element for access within its owning component:

html
<div x-data>
    <input live:ref="search" live:model="Search" />
    <button type="button" x-on:click="$live.$refs.search.focus()">Focus search</button>
</div>

From plain JavaScript, use Live.find(componentId).refs.search. Names are component-local, including teleported elements, and should be unique within that component. Reacquire refs after updates rather than retaining a reference to an element that may have been replaced. A ref is a DOM reference, not serializable server state.

Replacing DOM (live:replace) ​

live:replace discards and recreates an element's children from the new render rather than morphing them individually. .self replaces the entire element:

html
<div live:replace>
    <span>@Model.Count</span>
</div>
<div live:replace.self>Recreate this element too</div>

Replacement loses client-only element state, focus, and external widget instances in the replaced subtree. It also means newly created elements can run live:init again. Use it only when recreation is intentional; prefer live:ignore for a widget that must retain its own DOM. Do not combine replacement and ignore directives on the same element.

Sorting (live:sort) ​

Use a sortable container, stable item IDs, and an action accepting the moved ID (a string) and its zero-based destination position. Elements with live:sort:item must be direct children of the live:sort container:

html
<ul live:sort="Reorder" aria-label="Task order">
    @foreach (var task in Model.Tasks)
    {
        <li live:key="task-@task.Id" live:sort:item="@task.Id">
            <button type="button" live:sort:handle aria-label="Move task up or down">↕</button>
            <span>@task.Title</span>
        </li>
    }
</ul>
csharp
public async Task Reorder(string id, int position)
{
    // Application-specific: authorize the list and item, validate position,
    // persist the new order atomically, then render the authoritative order.
    await SaveTaskOrder(id, position);
}

SaveTaskOrder above is your application's operation, not a framework method. Never trust browser-supplied IDs or positions; check membership, ownership, and bounds before writing. Keep the result ordered consistently when rendering.

Pointer input uses native HTML drag-and-drop. An optional live:sort:handle restricts where dragging starts. Keyboard users can focus an item/handle and use ArrowUp/ArrowDown to move it. This is sorting within one container, not cross-list transfer or a touch-specific sortable library; test pointer behavior on your target devices and retain the keyboard controls.

Teleport ​

Render markup elsewhere in the document while keeping it owned by the originating Live component:

html
<div>
    <button type="button" live:click="$toggle('Open')">Open details</button>
    <template live:teleport="body">
        <section live:show="Open" role="region" aria-label="Details">
            <p live:text="Title"></p>
            <button type="button" live:click="$set('Open', false)">Close</button>
        </section>
    </template>
</div>

The target is a CSS selector and must exist. Use live:teleport on a <template>; its contents appear at the destination, not inside the original component root. Actions, models, refs, and client bindings inside remain associated with the originating component. Removing the template/component or navigating away must remove its teleported content too.

Use stable live:key values when conditionally rendering multiple teleport templates. Do not target another component's morph-managed contents unless that destination is protected with live:ignore. Prefer a stable destination outside Live roots. Teleport is a DOM-placement feature, not a modal library: dialogs still need accessible labeling, focus management, focus restoration, keyboard dismissal, and background interaction handling. Component-scoped CSS cannot reach content moved outside its physical scope; use explicit global classes for that content.

Alpine.js ​

Alpine works inside components. $live reads and changes the component from Alpine:

html
<div x-data>
    <span x-text="$live.Count"></span>
    <button x-on:click="$live.Increment()">+</button>
    <button x-on:click="$live.Count = 0; $live.$commit()">Reset</button>
</div>

Reading a property returns its value, assigning sets it for the next request (like live:model), and any other name calls that action. $live.$refresh() and $live.$commit() send a request. To confirm before an action, stop the click in Alpine:

html
<button live:click="Delete(@post.Id)" x-data x-on:click="if (!confirm('Delete this post?')) $event.stopImmediatePropagation()">Delete</button>

For shared Alpine state use $live.$entangle("Name"), or .live to commit changes immediately:

html
<div x-data="{ title: $live.$entangle('Title').live }">
    <input x-model="title" />
</div>

The value is initialized from the component and stays synchronized in both directions. Without .live, local changes are sent with the next component request. Entanglements are released when Alpine removes the element.

JavaScript API ​

Live.dispatch(name, data, to)Dispatch an event to listening components (and as a window event). to limits it to components with that name ("order-status") or one instance ("@" + id).
Live.find(id), Live.all()Component objects (data, memo, commit(calls)).
Live.find(id).get(path), .set(path, value)Read state including pending edits, or set a value for the next commit.
Live.find(id).cancelUpload(property)Cancel an in-progress upload for that property.
Live.find(id).refs.nameFind an element declared with live:ref="name"; Alpine can use $live.$refs.name.
Live.navigate(url)Navigate to another same-origin page without reloading the runtime.
Live.init(element)Initialize freshly inserted component markup containing signed snapshots.
Live.hook(name, callback)Subscribe to a lifecycle hook; returns an unsubscribe function.
live:error window eventA request failed (detail.status, detail.body).
live:upload-error window eventAn upload was refused (detail.message).

live:init fires on document after the JavaScript API is ready, before the first components initialize. Hooks receive { component }; morph hooks also receive { el }:

html
<script>
document.addEventListener("live:init", () => {
    Live.hook("component.init", ({ component }) => initializeWidgets(component.el));
    Live.hook("morph.updated", ({ el }) => initializeWidgets(el));
    Live.hook("component.destroy", ({ component }) => disposeWidgets(component.el));
});
</script>

Available hooks are component.init, component.destroy, morph.updating, and morph.updated. Widget initialization should be idempotent. The morph hooks surround a component's entire DOM update.

How It Works ​

  1. The first render runs Boot and Mount, renders the view, and adds live:id, live:snapshot (the state and some bookkeeping as JSON), and live:checksum (a signature made with the app's Data Protection keys) to the root element.
  2. An action sends the snapshot, the checksum, the changed properties, and the calls to POST /_live/update, with the CSRF token in the RequestVerificationToken header. Independent components committing in the same browser turn are bundled into POST /_live/batch (up to 50 per batch).
  3. The server checks the signature, restores the component (models are fetched again), applies the updates with their hooks, runs the actions, renders the view, and returns the HTML, a new snapshot, and the effects (events, redirect, download, and buffered stream frames). Computed caches belong to this restored instance only. Actions using Stream() can emit NDJSON frames before the final response; each such component uses its own update request.
  4. live.js patches the DOM with morphdom, keeping the focused input and child components, and fires the events.

A request runs through the normal pipeline, so Auth, the database, and every facade work in components. Requests of one component are sent one at a time, in order. Each entry in a batch still verifies its own signature and persistent middleware, and returns its own status; a batch is not a transaction. Because the signature uses the Data Protection keys, every server must share them (see deployment).

Testing ​

DotBlaze.Testing drives a component over HTTP the way live.js does, like Livewire's Livewire::test: it reads the component's snapshot from a page, sends updates and calls to /_live/update, and checks the returned state, HTML, errors, and effects:

csharp
var counter = await app.Client().Live("/", "counter");
await counter.Call("Increment");
counter.AssertSet("Count", 1).AssertSee("1");

var form = await app.Client().ActingAs(user).Live("/posts/create", "post-form");
await form.Set(new { Title = "" });
form.AssertHasErrors("Title");

See Testing Live Components for every method. tests/Browser/live.dom.js checks DOM morphing; live.features.js checks browser behavior against deterministic HTTP fixtures (using the sample's built Alpine asset). live.directives.js covers the directive reference, scoped CSS boundaries, Teleport/Alpine lifecycle, pointer/keyboard sorting, downloads, and streaming success/error/cancellation. live.e2e.js drives the running sample end to end. live.server-features.e2e.js exercises computed caching/invalidation, scoped styles, directives, Teleport, real downloads, and incremental streaming against the real /_live endpoints (no HTTP mocks). All five run with npm test in tests/Browser (job browser in CI). The sample must run in Testing (APP_ENV=Testing); the feature fixture at /_testing/live-features is not routed in other environments. Use a separate test database/storage, mail.default=log, queue.default=sync, and pass BASE_URL and SERVER_LOG to the browser tests. Optional E2E_SCREENSHOT saves the feature page screenshot. The server-side LiveComputedStylesTest and LiveEffectsTest cover computed invalidation/isolation, styles, download validation, signed snapshots, incremental output, and stream failures.

Complete Example: Counter From Class to Browser ​

In the Blog template, create:

csharp
// app/Live/DocumentationCounter.cs
using DotBlaze;

namespace Blog.LiveComponents;

public class DocumentationCounter : LiveComponent
{
    public int Count { get; set; }
    public void Increment() => Count = checked(Count + 1);
    public void Reset() => Count = 0;
}
html
<!-- resources/views/live/documentation-counter.blade.html -->
@model Blog.LiveComponents.DocumentationCounter
<section>
    <p role="status">Count: {{ Model.Count }}</p>
    <button type="button" live:click="Increment">Add one</button>
    <button type="button" live:click="Reset">Reset</button>
    <span live:loading>Updating...</span>
</section>

Add <live:documentation-counter /> inside the home page's content section. The generated layout already renders {{ Live.Scripts() }} and _ViewImports.cshtml enables DotBlaze tag helpers. Run dotnet build and dotblaze serve; clicking “Add one” changes the count without reloading the page.

In a test method using the Blog test project:

csharp
using var app = new DotBlaze.Testing.TestApp<Program>();
var counter = await app.Client().Live("/", "documentation-counter");
await counter.Call("Increment");
counter.AssertSet("Count", 1);
await counter.Call("Reset");
counter.AssertSet("Count", 0);

Count is intentionally client-editable demo state. For a record-editing component, lock the record identity and authorize each action; use the sample post form as the complete model-backed example.