Tag Helpers and View Components, Revisited: Active Translation with HTMX and SignalR
I wanted to wrap a forum post in a tag and have it turn French while I was reading the page. The English should show up straight away. Then, a moment later, bonjour. Just that post changes.
<active-translate language="fr" description="An informal forum reply">
<p>@Model.Message</p>
</active-translate>
If you've read my paging posts, this might look familiar. I like giving the caller a nice little tag and putting the actual HTML in a View Component's .cshtml file. Once you're writing a loop inside a C# string full of escaped quotes, it's probably time to go back to Razor. The paging Tag Helper and the page-size follow-up.
The fun bit this time is that some of the HTML arrives later. Razor queues the translation as it renders the page. When the worker has saved the French, SignalR gives the browser a nudge and HTMX swaps it in. The companion repo has a demo with fixed translations so you can see that happen without downloading a model.
Do I actually need to write a Tag Helper?
For the little status display in the demo, I already have a View Component called ActiveTranslationStatusViewComponent. Razor can call it either way.
<vc:active-translation-status></vc:active-translation-status>
@* Or, equivalently *@
@await Component.InvokeAsync("ActiveTranslationStatus")
For the tag syntax, register the assembly in Views/_ViewImports.cshtml.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, mostlylucid.activetranslatetag
| What you have | What I'd reach for |
|---|---|
| A model and some markup to reuse | <partial> |
| A component that prepares its own data | <vc:...> |
| A block of Razor you want to wrap and capture | A custom Tag Helper, with a View Component if you want a Razor template |
The translation tag is that last one. Its input is whatever Razor renders between the opening and closing tags. In the example that's the paragraph and the already-encoded forum message inside it. The helper captures both and hands them to the component. View Components and the Partial Tag Helper.
A little Tag Helper, a normal Razor view
Here's the whole helper. Most of it is just the properties you can set on the tag.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using mostlylucid.activetranslatetag.Active;
[HtmlTargetElement("active-translate")]
public sealed class ActiveTranslateTagHelper(IViewComponentHelper components)
: TagHelper
{
public string Language { get; set; } = "fr";
public string SourceLanguage { get; set; } = "en";
public string? Description { get; set; }
public string Mode { get; set; } = "active";
public string? Id { get; set; }
[HtmlAttributeName("class")]
public string? CssClass { get; set; }
[ViewContext, HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; } = null!;
public override async Task ProcessAsync(
TagHelperContext context, TagHelperOutput output)
{
var content = await output.GetChildContentAsync();
((IViewContextAware)components).Contextualize(ViewContext);
var model = new ActiveTranslationInput(
content.GetContent(), Language, SourceLanguage,
Description, Mode, Id, CssClass);
var rendered = await components.InvokeAsync(
"ActiveTranslate", new { model });
output.TagName = null;
output.Content.SetHtmlContent(rendered);
}
}
The interesting line is GetChildContentAsync(). That runs the Razor inside the tag. Contextualize(ViewContext) gives the component helper the current view context, which Razor normally supplies when you use Component.InvokeAsync in a view. The new { model } argument matches the component's model parameter. The contextualization API.
Finally, TagName = null drops the custom wrapper and SetHtmlContent writes the component's rendered IHtmlContent. At this point Razor has already encoded the forum message. Encoding the whole result again would show the reader the literal <p> tags.
The input carries the already-rendered child HTML and the tag's options:
public sealed record ActiveTranslationInput(
string Html,
string Language = "fr",
string SourceLanguage = "en",
string? Description = null,
string Mode = "active",
string? Id = null,
string? CssClass = null);
The component takes that record in InvokeAsync(ActiveTranslationInput model) and returns View(viewModel). You can also call it directly with <vc:active-translate model="@input"></vc:active-translate> if you already have an ActiveTranslationInput containing rendered HTML.
The HTML belongs in the view
The component template lives at Views/Shared/Components/ActiveTranslate/Default.cshtml. Here's where the wrapper and its HTMX attributes come from.
@model mostlylucid.activetranslatetag.Active.ActiveTranslationViewModel
<div id="@Model.Id" class="@Model.CssClass"
lang="@Model.Language"
data-translation-id="@Model.TranslationId"
data-translation-state="@Model.State"
data-translation-language="@Model.TargetLanguage"
data-translation-token="@Model.Token"
hx-get="@Model.FragmentUrl"
hx-trigger="@(Model.Token == null ? null : "translation-ready")"
hx-swap="@(Model.Token == null ? null : "innerHTML")"
hx-sync="@(Model.Token == null ? null : "this:replace")"
aria-live="polite" aria-busy="@(Model.State == "pending" ? "true" : "false")">
@Model.Content
</div>
If I want to change the class or the loading state, I edit this view. A consuming app can put its own template at the same path and pick up the same view model. Razor Class Libraries and view overrides.
The hx-* attributes appear when the component has a token for pending work. So how did the work get there?
Put the job on the queue while Razor renders
By the time the component runs, it has the whole post. It extracts the text, works out a key from the post and its translation options, and asks SQLite if it already has the result. A cache hit goes straight into the view. Here's what happens on a miss.
var html = await store.GetHtmlAsync(request.Id, ct);
if (html == null)
{
await store.SaveRequestAsync(request, ct);
var work = await queue.EnqueueAsync(request.Id, ct);
// In active mode we can render the original while work is pending.
}
That await gets the handle to the queued job. The component can carry on rendering while the job runs. If you're curious what it looks like to wait for the result, add mode="server" to the same tag.
The queue uses a bounded Channel<string> of translation keys. Two copies of the same post share a job, which is handy when the demo shows the same greeting twice. If the channel is full, the original stays visible and a later page render can try again.
A BackgroundService registered as a hosted service drains the channel. The sample targets .NET 11, so I used a C# 15 union for the result.
public sealed record TranslationReady(string Html);
public sealed record TranslationFailed(string Message);
public union TranslationResult(TranslationReady, TranslationFailed);
If it's ready, there's HTML to render. If it failed, there's a message and the original post stays visible. The compiler checks that the component and worker handle both cases in their switches. C# 15 union types.
The worker opens a DI scope for the provider, translates the text, and saves the result. On the success path, these are the two calls that matter.
await _store.SetHtmlAsync(id, html, ct);
await _hub.Clients.Group(id)
.TranslationReady(new TranslationNotice(id))
.WaitAsync(stoppingToken);
Save first, ping second. By the time the browser hears about it, the HTML is ready to fetch. The typed hub client gives the worker and the hub the same C# method for that notification. You can close the tab and the worker can still finish. SQLite keeps the finished result for the next visit. SignalR from a hosted service.
A bit of HTMX and SignalR
The browser is looking at an English post. It already has the URL of the French fragment, so all it needs is the word when that fragment is ready.
sequenceDiagram
participant R as Razor render
participant W as Hosted worker
participant B as Browser
participant H as SignalR hub
participant F as Minimal API
R->>W: Queue translation on cache miss
R-->>B: Original content with HTMX attributes
B->>H: Watch the fragment token
W->>W: Translate text and save HTML
W-->>B: TranslationReady for the content key
B->>F: HTMX GET using the fragment token
F-->>B: Completed HTML
There's a little race here. The worker might finish before SignalR connects, particularly with our demo provider. Watch joins the group first and then checks the cache. A late arrival gets the same ready event as somebody who was already listening. If the job has failed, the original post stays put.
The demo calls app.MapActiveTranslation() to wire up the hub and one Minimal API route.
endpoints.MapGet(ActiveTranslationFragment.Path, ActiveTranslationFragment.GetAsync);
endpoints.MapHub<ActiveTranslationHub>(ActiveTranslationHub.Path);
That GET validates the token and looks up the HTML. It returns 204 No Content if the result is missing, or text/html when it's ready. The successful response also sends HX-Trigger: translation-swapped so the demo can clear the busy state and update the wrapper's language. Minimal API responses.
On the browser side, those Razor attributes come out like this.
<div hx-get="/_active-translate/fragment?token=…"
hx-trigger="translation-ready"
hx-swap="innerHTML">
<p>Hello, forum!</p>
</div>
When SignalR says the translation is ready, the bridge runs one line for each pending wrapper with that key.
window.htmx.trigger(element, "translation-ready");
HTMX sees translation-ready, makes the GET and puts the returned HTML inside that div. That's the bit I like. The event carries a key and the request carries a token. Both describe work the server already started when Razor rendered the post. HTMX 4 swap reference.
Have a play
Clone the companion repo and run it with the .NET 11 SDK and Node.js for the frontend asset build. The repo starts at SDK 11.0.100 and accepts later .NET 11 SDKs.
npm ci
npm run build
dotnet run --project src/mostlylucid.activetranslatetag.Demo
On the first visit, watch the English posts turn French. The greeting appears twice, so you can see one job update two places. Refresh after the swaps and SQLite serves the translations during the render.
The sample uses fixed French text. If you fancy trying a real model, the README shows how to select Ollama, LLamaSharp or ONNX Runtime GenAI behind the same provider interface. The worker sends the model text fragments and keeps the markup on the server. That preserves links and tags, though translating the words on either side of an inline link separately can make the French a bit awkward.