
Editorial illustration.
Originally published 23 June 2023; rewritten and reviewed on 15 October 2026.
A user types three characters into a customer lookup box, pauses for half a second, and then backspaces to type a completely different name. Two hundred milliseconds later, the slow response from the first request arrives and overwrites the dropdown under the new text. The browser did nothing illegal, and the server returned valid JSON, yet the user just clicked the wrong company record and saved an invoice against it.
That race condition is the main reason I stopped treating autocomplete as a quick jQuery or fetch snippet. In ASP.NET MVC and Razor Pages applications—especially internal billing, HR, or clinic systems where staff type fast all day—relevance and request ordering are part of the contract.
Triggering the lookup without hammering the server
Waiting for at least three characters before hitting the database is a sensible baseline for names, SKUs, or Malaysian IC/registration prefixes, because one or two characters match thousands of rows and force SQL Server to scan half the table. Still, trim whitespace first (query.trim().length >= 3), otherwise someone typing " a" fires a useless query.
A short debounce—usually 250ms to 300ms—absorbs normal typing bursts without making the UI feel sluggish. On the ASP.NET MVC side, keep the endpoint read-only, cap the result count, and project only the fields the dropdown actually needs:
[HttpGet]
public async Task<IActionResult> SearchClients(string? q, CancellationToken ct)
{
var term = (q ?? string.Empty).Trim();
if (term.Length < 3 || term.Length > 80)
{
return Json(Array.Empty<object>());
}
var tenantId = User.GetTenantId();
var results = await _db.Clients
.AsNoTracking()
.Where(c => c.TenantId == tenantId && c.IsActive && EF.Functions.Like(c.Name, $"%{term}%"))
.OrderBy(c => c.Name)
.Take(10)
.Select(c => new { id = c.Id, label = $"{c.Name} ({c.Code})" })
.ToListAsync(ct);
return Json(results);
}
Notice two details that get skipped in tutorials: passing CancellationToken ct so EF Core can abort an in-flight SQL query if the client disconnects, and filtering by TenantId and IsActive on the server. Never rely on the UI hiding inactive or cross-tenant records.
Cancelling stale responses on the client
Debouncing reduces how many requests leave the browser, but it does not stop two requests from overlapping on a flaky mobile connection or an overloaded IIS worker. If request A takes 700ms and request B takes 90ms, request A arrives last and wins unless you cancel it or check a sequence counter.
Modern fetch makes cancellation straightforward with AbortController:
let activeController = null;
let debounceTimer = null;
input.addEventListener("input", () => {
clearTimeout(debounceTimer);
const term = input.value.trim();
hiddenIdInput.value = ""; // clear previous selection when user edits text
if (term.length < 3) {
clearSuggestions();
return;
}
debounceTimer = setTimeout(async () => {
if (activeController) {
activeController.abort();
}
activeController = new AbortController();
try {
const res = await fetch(`/Clients/SearchClients?q=${encodeURIComponent(term)}`, {
signal: activeController.signal
});
if (!res.ok) return;
const items = await res.json();
if (input.value.trim() === term) {
renderSuggestions(items);
}
} catch (err) {
if (err.name !== "AbortError") {
showInlineError("Could not load suggestions. Try again.");
}
}
}, 280);
});
Clearing hiddenIdInput.value as soon as the user types again is crucial. Otherwise, a user can pick “Syarikat Maju Jaya” (ID 412), change their mind, edit the visible text to “Klinik Harmoni”, forget to click a new item, and submit the form with ID 412 still sitting in the hidden field.
Validating the selection on form submission
Render suggestion labels using textContent rather than innerHTML so a record with < or & in its name cannot break markup or introduce XSS. And when the form finally posts to your [HttpPost] action, treat the submitted ClientId as untrusted input: verify that the record exists, is still active, and belongs to the signed-in user’s tenant. Someone could have deactivated that client in another tab while the form was open.
Keyboard navigation and edge cases
Power users who enter data all day rarely reach for the mouse on every row. Wire up ArrowDown, ArrowUp, Enter, and Escape, keep aria-expanded and aria-activedescendant updated on the input, and announce empty states (“No matching clients”) politely instead of silently leaving a blank box.
Before shipping, test four awkward cases: rapid typing followed by immediate backspace below three characters, a simulated 500 error from the endpoint, two records with nearly identical names, and pressing Enter while the list is still loading. When those four behave cleanly, the autocomplete stops feeling fragile and starts saving people real time.