Blazor standard¶
This page sets the rules for Blazor components in ConnectSoft templates and in products built from them. It is written for engineers who write or review .razor and .razor.cs files. Composition of micro-frontends is in Micro-frontends; accessibility, RTL and layout are in Accessibility and RTL and Responsive layout.
Blazor is the default web UI, through the ConnectSoft Shell, micro-frontend and UIKit templates (ADR-0106). The hosting model is Blazor Server: interactive components run on the server over a SignalR circuit, and the page is prerendered before the circuit connects.
What Blazor Server changes¶
Three properties of Blazor Server explain most of the rules below:
- Events queue, they do not block. While a handler awaits an HTTP call, the circuit dispatches the next click. A second click on a save button runs the handler a second time.
- Attributes reach the browser late.
disabled="@isSaving"is sent only after the handler yields at its first await, and the browser then needs a render round trip to apply it. - The prerendered page is live-looking but not live. Until the circuit connects, a click on a rendered control is accepted by the DOM and discarded without an error.
Rules¶
CS-UI-001: Guard every write handler against re-entry¶
Severity: blocker · Applies to: blazor, template · Enforced by: bUnit test; manual (target: ENF-045) · Status: active
Why¶
A save, create, delete or submit handler that runs twice writes twice. A root create makes two records; a child write under a versioned aggregate is refused the second time and the refusal is often hidden by a modal that has already closed. On a slow connection the window is several seconds. Binding disabled alone does not close it, because the attribute reaches the browser only after the first await.
Do¶
- Check a busy flag and set it synchronously at the top of the handler, before the first
await. - Release the flag in a
finallyblock. - Bind the trigger's
disabledattribute to the same flag, so the user also sees that the action is running. - Prefer a shared single-flight helper over a hand-written flag in each component. The UIKit
AsyncButtonalready guards its own click this way.
Don't¶
- Rely on
disabled="@isSaving"as the only guard. - Set the busy flag after an await, or only inside a
tryblock that an early return can skip.
Example¶
private bool isSaving;
private async Task SaveOrderAsync()
{
if (this.isSaving)
{
return;
}
this.isSaving = true;
try
{
await this.OrdersClient.SaveAsync(this.model);
await this.OnSaved.InvokeAsync();
}
finally
{
this.isSaving = false;
}
}
<button type="button" data-testid="order-save" disabled="@isSaving" @onclick="SaveOrderAsync">Save</button>
How to check¶
- Every handler that writes has the entry check and the
finallyrelease. - A bUnit test holds the first call open (for example with a gated
HttpMessageHandler), clicks the trigger twice, and asserts that one request was sent.
CS-UI-002: Put component logic in a code-behind file¶
Severity: minor · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
Analyzers, XML documentation rules and navigation work better in a .cs file than in an @code block. Most ConnectSoft components already use a code-behind: 783 of 945 Razor files in the templates and UI kits have one.
Do¶
- Put fields, lifecycle methods, handlers and injected services in a
partial classinComponent.razor.cs. - Keep an
@codeblock only for a component that declares parameters and nothing else.
Don't¶
- Split one component's logic between an
@codeblock and a code-behind. - Put handlers or service calls in
@code.
How to check¶
Review new .razor files: an @code block contains only [Parameter] properties.
CS-UI-003: Set the render mode once on <Routes>¶
Severity: minor · Applies to: blazor, template · Enforced by: manual (target: ENF-046) · Status: active
Why¶
Shell hosts set InteractiveServer on <Routes> and <HeadOutlet> in App.razor, which makes every routed page interactive. A page that also declares @rendermode repeats that setting and can drift from it when the host changes.
Do¶
- Set the render mode in
App.razoron<Routes>and<HeadOutlet>. - Leave prerendering on (the default).
Don't¶
- Add
@rendermodeto pages, layouts or micro-frontend components. - Turn prerendering off to hide a hydration problem; fix the component instead (CS-UI-004).
Example¶
How to check¶
- Search the change for lines starting with
@rendermodeoutsideApp.razor. - The render mode in
App.razordoes not setprerender: false.
CS-UI-004: Keep the first render hydration-safe¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
The page is prerendered on the server, where there is no browser. JavaScript interop and browser storage throw during prerender, and a value read before the user's identity is hydrated is read under the wrong key and never read again.
Do¶
- Call JavaScript interop and read
localStorageorsessionStorageonly inOnAfterRenderAsyncwhenfirstRenderis true, or later. - Render a neutral state during prerender, for example the host defaults or a skeleton.
- When a stored value is keyed by the user, re-read it when the key changes after the identity is hydrated.
Don't¶
- Call
IJSRuntimeor a storage service inOnInitialized,OnInitializedAsyncorOnParametersSet. - Restore state once and assume the key was final.
Example¶
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
this.savedFilter = await this.Storage.GetAsync<OrderFilter>(this.FilterKey);
this.StateHasChanged();
}
}
How to check¶
- Search lifecycle methods other than
OnAfterRenderAsyncforJS.Invoke,IJSRuntimeand storage calls. - A bUnit test with
JSInterop.Mode = JSRuntimeMode.Strictrenders the component without unplanned interop.
CS-UI-005: Never use ConfigureAwait(false) in components¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: retired
Replaced by: CS-ASY-002. The component rule is part of the async rule for grains and components.
CS-UI-006: Mark interactive elements and page roots with data-testid¶
Severity: minor · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
End-to-end and bUnit tests need a locator that survives text changes, translation and restyling. A component reached only through a page branch needs a root marker, or no test can tell that it opened.
Do¶
- Give every button, link, input, select and other interactive element a
data-testid. - Give every page and modal root a
data-testid. - Use stable kebab-case values that name the thing, for example
order-saveorcustomer-search. - When a value is rendered from a bool or an enum, render every branch as an explicit string.
Don't¶
- Locate elements in tests by visible text, CSS class or DOM position when a
data-testidcan be added. - Reuse one
data-testidfor two different controls on the same page, except for the same control rendered once per responsive branch (see CS-A11Y-014).
How to check¶
- Review new markup for interactive elements without
data-testid. - New
data-testidvalues are unique on their page, except for the same control rendered once per responsive branch.
CS-UI-007: Show no field that has no save path¶
Severity: blocker · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
A form that accepts a value and closes on success confirms something that did not happen. The user then acts on it, for example tells a customer that a setting was changed. This is worse than a refusal.
Do¶
- Trace every input to a property of the request that the form sends.
- Remove an input that no request carries, and show text that says how the value can be changed instead.
- Test both halves: the input is absent and the explanation is present.
Don't¶
- Keep an input from a superseded model "for later".
- Assert only that the input is gone; a modal that never rendered passes that assertion too.
How to check¶
For each input in the change, find the request property it is mapped to.
CS-UI-008: Validate the record the server will store¶
Severity: major · Applies to: blazor, service, template · Enforced by: manual · Status: active
Why¶
A form that validates only the fields the user touched lets a record through that the server then refuses, often with an untranslated message. Old, seeded or migrated records are where "impossible" states actually exist.
Do¶
- Apply the same rule as the server, to the whole record that will be saved.
- When a stored value is outside a select's option list, render the stored value as its own option instead of a blank.
Don't¶
- Skip validation of untouched fields so that an old record "stays editable".
- Show success before the service confirms the save.
How to check¶
A test edits a record that breaks a rule in a field the edit does not touch, and asserts the form reports it.
CS-UI-009: Round-trip every field that an edit form does not change¶
Severity: blocker · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
Most amend endpoints replace the whole record. A view model built for display (rounded values, placeholder text, missing fields) loses data on every save: a field the client cannot hold is a field an edit destroys. A picker whose options use a different id space from the stored value opens blank and re-assigns the record on save.
Do¶
- Make the view model lossless before building an editor over it: it holds every field the server assigns on update.
- Prefill every input from the stored value.
- Build picker options in the same id space as the stored value, and keep the current value as an option even when it is no longer offered.
Don't¶
- Send
nullor a default for a field the form does not show. - Edit through a display model.
How to check¶
Read a record, open its editor, save without changes, read it again and compare every field. Automate this as a test for each editor.
CS-UI-010: Send the revision the form loaded¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
A form opened before a colleague's save silently undoes that save when it sends a full record. Optimistic concurrency stops this only when the form sends the revision it loaded. A read model that drops the revision turns the check off without any error.
Do¶
- Keep the loaded revision with the form and send it as the expected revision.
- On a 409 conflict, keep the form open, show the refusal and offer a reload.
Don't¶
- Close the form or clear the user's input on a conflict.
- Map a read model that omits the revision.
How to check¶
A test asserts the revision value in the request body, and a test of the 409 path asserts that the form stays open with a reload action.
CS-UI-011: Read a call's results from the call, not from shared state¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
Two loads on one page often overlap: a filter change, a second picker, a run button. A total left on a shared client property is overwritten by whichever response lands last, so one request's rows are shown with another request's count. A slow old load that finishes after a new one puts stale rows back on the screen.
Do¶
- Return everything a caller needs from the call itself, for example
(Rows, Total). - Give each load a monotonic ticket and let only the newest load write the screen, including the loading flag.
- When a test waits for a load, wait on a value the load is guaranteed to change, not on an element that is already visible.
Don't¶
- Read a property of a shared client after an await to get data about the call you awaited.
How to check¶
A bUnit test starts two overlapping loads, completes them in reverse order and asserts the screen shows the newest one.
CS-UI-012: Dispose subscriptions and JavaScript object references¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
A component that subscribes to a singleton or circuit-scoped event and never unsubscribes keeps running after it leaves the page, and re-renders a disposed component. An IJSObjectReference that is never released leaks in the browser.
Do¶
- Implement
IDisposableto unsubscribe from events and cancel timers andCancellationTokenSources. - Implement
IAsyncDisposableto disposeIJSObjectReferenceandDotNetObjectReferenceinstances, and catchJSDisconnectedExceptionthere.
Don't¶
- Subscribe in
OnInitializedwithout a matching unsubscribe.
How to check¶
- For every
+=on an event and every JavaScript module import in the change, find the matching release. - Also find the release of every new timer,
CancellationTokenSourceandDotNetObjectReference.Createcall.
CS-UI-013: Expose component events as EventCallback¶
Severity: minor · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
EventCallback runs on the renderer, awaits async handlers and re-renders the parent. An Action or Func parameter does none of this, so the parent shows stale state after the event.
Do¶
- Declare component events as
EventCallbackorEventCallback<T>. - Invoke them with
InvokeAsyncand await the result.
Don't¶
- Declare
ActionorFuncparameters for events.
How to check¶
Search new [Parameter] declarations for Action and Func types.
CS-UI-014: Mark required parameters with [EditorRequired]¶
Severity: minor · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
Without [EditorRequired] a caller can omit a parameter the component cannot work without, and the compiler does not warn.
Do¶
- Add
[EditorRequired]to every parameter without which the component cannot render correctly. - Pass data to a component through
[Parameter]. Use[CascadingParameter]only for state that every descendant needs, such as the authentication state or a form context.
Don't¶
- Use a cascading value to avoid passing a parameter through one or two levels.
How to check¶
Review new components for parameters that are dereferenced without a null check and lack [EditorRequired].
CS-UI-015: Keep Razor comments outside an open tag¶
Severity: blocker · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
Razor does not treat a comment inside a tag's attribute list as a comment. It reads it as an attribute name, and the component throws at render, which takes down the whole circuit. A bUnit test that renders the component directly with parameters does not see the bad call site.
Do¶
- Put a comment above the tag it describes.
- Cover a component that is reached only through a page branch with a test that renders the page and opens it.
Don't¶
- Place
@* ... *@between the attributes of an element or a component.
Example¶
@* The customer picker is read-only after the order is confirmed. *@
<CustomerPicker Value="@customerId"
Disabled="@isConfirmed" />
How to check¶
Search for lines whose trimmed text starts with @* while the previous tag is still open.
CS-UI-016: Delete or wire up a private handler that nothing calls¶
Severity: major · Applies to: blazor, template, service · Enforced by: manual · Status: active
Why¶
An unused private method with a business name is a feature wired to nothing: the code was written, documented and reviewed, and the screen still shows nothing. The analyzer warning that would report it is easy to miss among other warnings.
Do¶
- Treat an unused private method warning (S1144, IDE0051) as a defect to fix, not as noise.
- Wire the method to its caller, or delete it.
Don't¶
- Suppress the warning on a method with a business name.
How to check¶
- Search the file for the method name: a private method that appears only in its own declaration is never called.
- Search the change for
S1144andIDE0051suppressions on methods with a business name.
CS-UI-017: Never present fallback data as live data¶
Severity: blocker · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
A component that catches a failed call and shows sample or cached data looks healthy while it is broken. EnsureSuccessStatusCode turns a 401 or a 403 into the same exception as an outage, so a denied request looks like a successful one.
Do¶
- Show an error state with a retry when a call fails.
- Show a refusal message when the call is refused (401 or 403).
- Keep sample data behind an explicit development-only setting that is off in every deployed configuration.
- Show an empty successful answer as empty.
Don't¶
- Catch
HttpRequestExceptionand fill the screen from a mock store. - Replace an empty successful answer with sample data.
How to check¶
Search catch blocks in UI clients and components for reads from sample or mock data.
CS-UI-018: Gate one act with one predicate at every entry point¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
An act is often reachable through several doors: a button, a quick-action picker, a deep link, a mobile twin. When only one door checks readiness, the user fills in a form that can only be refused at the end.
Do¶
- Put the readiness condition in one property and read it at every entry point, including routes that host the act.
- When the act is not available, show the control disabled with the reason on screen.
Don't¶
- Repeat the condition in two places that can drift.
- Remove a control silently when it is not available.
How to check¶
For a gated act, search every @page that hosts it for the predicate's name.
CS-UI-019: Make a control do what its label says¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
The label or placeholder is the specification users read. A search box that says "name or order number" but cannot find a full name, or an export button next to a filtered list that exports something else, is a defect even when every line of code is individually correct.
Do¶
- Test every input the label promises against data that is known to match.
- For free-text search, split the query into tokens and require every token to match some field.
- Name an export for what it produces, or make it honour the filters shown beside it.
Don't¶
- Assert only that an export starts with a zip header; assert its content against what the page states.
How to check¶
List the promises in each label and placeholder of the change and find a test for each.
CS-UI-020: Offer only assignable items in a picker¶
Severity: major · Applies to: blazor, template, service · Enforced by: manual · Status: active
Why¶
A picker that offers people who have left, or records that cannot take the assignment, lets a user assign work to someone who can never open it. The fix belongs in the backend-for-frontend list, so every picker that uses the list is fixed at once.
Do¶
- Filter the list at its source to items that can accept the assignment.
- Keep the currently assigned item visible on an edit form, even when it is no longer assignable (CS-UI-009).
- When a required picker cannot load its options, show the load failure with a retry.
Don't¶
- Offer a button that opens a form whose required picker can never be filled by that user.
How to check¶
A test lists the picker's options for a dataset that contains an unassignable item and asserts the item is absent.
CS-UI-026: Show a stored value that the option list does not contain¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
Seeded, imported and older records hold values that a fixed option list no longer offers. The browser shows no selection for such a value, and saving the form can overwrite it with the first option or with nothing.
Do¶
- When the stored value is not among the options, render it as its own option, marked as no longer offered, and keep it selected.
- Keep that value on save unless the user picks another option.
Don't¶
- Bind a select to a column with historical or free-text values and assume every value is in the list.
How to check¶
A component test renders the form with a stored value outside the list and asserts that the value is shown and is unchanged after a save without edits.
CS-UI-027: Restore a remembered choice once its key is known, and forget one the server refuses¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
A choice remembered in browser storage under a per-user key cannot be read before the user id hydrates, and a one-time restore on the first render reads the wrong key. A remembered choice that the user may no longer use is refused on every re-apply, and each refusal triggers another re-apply.
Do¶
- Read a remembered choice when its storage key becomes known, and read it again whenever the key changes.
- When the server refuses a restored choice, clear both the field and the stored value, and fall back to the default once.
Don't¶
- Restore only in
OnAfterRenderAsync(firstRender)when the key depends on the user. - Retry a refused choice on the next state change.
How to check¶
- A browser test stores a choice, reloads with delayed claims hydration and asserts that the choice is active.
- A second test stores a choice the user may not use and asserts that it is cleared and the page settles.
CS-UI-028: Back a circuit-scoped accessor with a plain AsyncLocal<T> value¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
An accessor that keeps a mutable holder in AsyncLocal and clears the holder in place also clears the value for every execution context that already copied it. On a Blazor circuit those include continuations of calls that are still running, which then lose the user's token or services.
Do¶
- Store the value itself in
AsyncLocal<T>, and set or clear it by assigning a new value. - Publish the value at the start of each circuit activity, as the Blazor circuit-handler pattern does.
Don't¶
- Copy the
HttpContextAccessorholder pattern, which clears in place on purpose, into a circuit-scoped accessor.
Example¶
public sealed class CircuitServicesAccessor
{
private static readonly AsyncLocal<IServiceProvider?> Current = new();
public IServiceProvider? Services
{
get => Current.Value;
set => Current.Value = value;
}
}
How to check¶
An accessor test publishes a value, awaits, clears the value from the publisher, and asserts that the continuation still reads it.
CS-UI-029: Never bind an event modifier to state that its own handler sets¶
Severity: minor · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
The browser decides :preventDefault and :stopPropagation before the .NET handler runs, from the value of the last render. A flag that the handler sets therefore applies to the next event, not to the current one.
Do¶
- Use a fixed modifier value, and correct the bound value in the handler, for example by re-applying the accepted text.
- When the decision must depend on the key, make it in a small JavaScript handler.
Don't¶
- Write
@onkeydown:preventDefault="this.rejectKey"when the keydown handler setsrejectKey.
How to check¶
A browser test types a rejected and then an accepted character and asserts the resulting value.
CS-UI-030: Give application components names that packages will not take¶
Severity: minor · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
A component tag resolves against every namespace imported in _Imports.razor. When a package version adds a component with the same name as an application component, Razor has two candidates for one tag, and the build fails with hundreds of errors in generated files.
Do¶
- Give application-owned components a prefix that names the application or the micro-frontend.
- Build in Release after each UI package bump.
Don't¶
- Name application components with generic names that a UI kit is likely to use, such as
Card,BadgeorTooltip.
How to check¶
New application components carry the application prefix.