JSON definition · shared/definitions/choices-from-web.json
View on GitHub
{
"title": "Choose an office",
"elements": [
{
"type": "panel",
"name": "find_office",
"elements": [
{
"type": "radiogroup",
"name": "region",
"title": "Region",
"colCount": 3,
"defaultValue": "europe",
"isRequired": true,
"choices": [
{
"value": "europe",
"text": "Europe"
},
{
"value": "americas",
"text": "Americas"
},
{
"value": "asia-pacific",
"text": "Asia-Pacific"
}
]
},
{
"type": "dropdown",
"name": "office",
"title": "Office",
"isRequired": true,
"choicesByUrl": {
"url": "/api/offices?region={region}",
"valueName": "id",
"titleName": "name"
}
}
]
},
{
"type": "dropdown",
"name": "country",
"title": "Your country",
"isRequired": true,
"choicesByUrl": {
"url": "/api/countries",
"valueName": "code",
"titleName": "name"
}
}
]
}
Client · shared/client/choices-from-web.js · sjs:choices-from-web.client
View on GitHub
// Use choicesByUrl in the form definition to load lists from API endpoints
// "choicesByUrl": { "url": "/api/offices?region={region}", "valueName": "id", "titleName": "name" }
// "choicesByUrl": { "url": "/api/countries", "valueName": "code", "titleName": "name" }
// SurveyJS replaces {region} with the selected region and reloads the office list when the region changes
// Optional: add your auth header to every choices request
import { settings } from "survey-core";
settings.web.onBeforeRequestChoices = (_, options) => {
options.request?.setRequestHeader("Authorization", `Bearer ${token}`);
};
Server · Endpoints/ChoicesFromWeb.cs · sjs:choices-from-web.server
View on GitHub
// GET /api/offices?region= — {region} from the form arrives as a query parameter
app.MapGet("/api/offices", async (string? region, SurveyDb db) =>
await db.Offices.Where(o => o.Region == (region ?? "")).OrderBy(o => o.Name).Select(o => new { o.Id, o.Name }).ToListAsync());
// GET /api/countries — a proxy: the browser can't call a service without CORS, your server can
app.MapGet("/api/countries", async (IMemoryCache cache, IHttpClientFactory http, ILoggerFactory logs, IWebHostEnvironment env, HttpResponse response) =>
{
response.Headers.CacheControl = "public, max-age=86400";
try
{
return await cache.GetOrCreateAsync("countries", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(1);
var all = await http.CreateClient("restcountries").GetFromJsonAsync<RestCountry[]>("https://restcountries.com/v3.1/all?fields=name,cca2");
return all!.Select(c => new Country(c.Cca2, c.Name.Common)).OrderBy(c => c.Name, StringComparer.Ordinal).ToList();
});
}
catch (Exception e) // down, or a different answer: serve the bundled list for 10 minutes, so requests don't each wait for the timeout
{
logs.CreateLogger("ChoicesFromWeb").LogWarning(e, "restcountries.com failed; serving shared/seed/countries.json");
return cache.Set("countries", BundledCountries(env), TimeSpan.FromMinutes(10));
}
});