
Editorial illustration.
Originally published 23 June 2023; rewritten and reviewed on 15 October 2026.
A user opens a Malaysian address form, selects Selangor, realizes they meant Sarawak, and switches the state dropdown half a second later. If the Selangor request takes 600ms and the Sarawak request takes 150ms, the slower Selangor response arrives last and overwrites the city list with Shah Alam and Petaling Jaya—while the state dropdown still says Sarawak.
Cascading dropdowns are trivial when you click once in a local demo. In production, they need to survive rapid changes, slow mobile networks, empty datasets, and edit forms where both values already exist in the database.
Reset the dependent field and guard against stale responses
The moment the parent <select> changes, clear the old child options immediately, disable the child control, and show a clear loading state. Never leave Petaling Jaya selectable under Sarawak while a network call is in flight.
With jQuery, you can prevent race conditions using either a request counter or by aborting the previous jqXHR object. Using a version counter is simple and works cleanly with async/await:
let requestVersion = 0;
async function loadCities(stateId, preselectedCityId = '') {
const version = ++requestVersion;
const $city = $('#city');
const $status = $('#city-status');
$city.empty().append(new Option('-- Select city --', '')).prop('disabled', true);
$status.text('');
if (!stateId) return;
$city.find('option:first').text('Loading cities…');
try {
const rows = await $.getJSON('/api/locations/cities', { stateId });
if (version !== requestVersion) return;
$city.empty();
if (!rows || rows.length === 0) {
$city.append(new Option('No cities available', ''));
return;
}
$city.append(new Option('-- Select city --', ''));
for (const row of rows) {
$city.append(new Option(row.name, row.id));
}
if (preselectedCityId) {
$city.val(String(preselectedCityId));
}
$city.prop('disabled', false);
} catch {
if (version !== requestVersion) return;
$city.empty().append(new Option('-- Unable to load cities --', ''));
$status.text('Could not load cities for this state. Please re-select to retry.');
}
}
$('#state').on('change', function () {
loadCities(this.value);
});
Building <option> elements with new Option(row.name, row.id) instead of string concatenation ('<option value="' + row.id + '">' + row.name + '</option>') avoids accidental HTML injection if a lookup name ever contains an ampersand or angle bracket.
Handle edit forms deliberately
One place cascading dropdowns often break is the Edit screen. On a Create page, both dropdowns start empty. On an Edit page, the server renders StateId = 10 and CityId = 142 in the model.
If your JavaScript simply runs $('#state').trigger('change') on page load without passing the saved cityId, the dropdown resets and loses the user’s existing city. Instead, render the saved cityId in a data-selected-city attribute (or a Razor model variable) and call loadCities($('#state').val(), $('#city').data('selected-city')) once on initialization, or better yet, render the initial state’s cities directly on the server in Razor so the Edit form is immediately usable before JavaScript even executes.
Validate the relationship on the server
Filtered <select> options in the browser are a UI convenience, not a security boundary. Anyone can open DevTools or replay a POST request with StateId=13 and CityId=42 where city 42 belongs to another state—or to a deactivated branch the user is not allowed to choose.
In your C# ASP.NET MVC controller, always verify that the pair is valid before saving:
bool validPair = await _db.Cities
.AnyAsync(c => c.Id == model.CityId && c.StateId == model.StateId && c.IsActive);
if (!validPair)
{
ModelState.AddModelError(nameof(model.CityId), "Selected city does not belong to the chosen state.");
return View(model);
}
If your lookup tables rarely change (like states and districts), cache the JSON endpoint or query with IMemoryCache so rapid keyboard navigation up and down the parent <select> does not hammer SQL Server on every arrow-key press.
Test transitions, not just the happy path
Before calling the form done, test what happens when:
- A user resets the parent dropdown back to
-- Select state --(the child must clear and disable). - A parent has zero matching children (for example, certain federal territories or categories without subcategories).
- The API returns a
500error (the user should see a readable message, not a frozen spinner). - Someone holds down the Down Arrow key on
#state, firing five requests in one second (only the final state’s cities should appear).
A reliable cascading dropdown does more than fetch a list on change. It keeps the DOM honest while requests are in flight, discards outdated responses, and enforces the relationship on the server.