Integrate SurveyJS with ASP.NET Core

SurveyJS libraries enable you to display and edit web forms, collect answers, analyze results, and generate PDF forms in the browser. Your backend supplies the data these libraries need and stores the changes they produce. The libraries exchange JSON with your backend, which allows you to use any database and storage services.

This guide explains how to integrate SurveyJS with your ASP.NET Core backend. It walks through all backend-specific workflows, starting with the minimum integration: saving a completed response. Each workflow description provides client and server code samples and a link to a live example.

Run Forms

SurveyJS Form Library displays a form using a JSON schema and collects the respondent's answers. Start integration by adding an endpoint that saves those answers. You can then load data from the server, save progress in unfinished forms, and add the other features described below if your application needs them.

Save Responses

To collect responses, your backend needs an endpoint that accepts and stores answers. The form JSON schema can be a JavaScript constant on the page for now—this first step does not require an endpoint for loading it.

When the respondent completes the form, SurveyJS raises the onComplete event. Handle it to send survey.data and the form ID to your save endpoint. The backend should store the answers as a single JSON document and return the saved response's ID to confirm that the save succeeded.

Store the response exactly as it arrives—spaces, empty strings, and empty objects may be meaningful.

Client code
// Define the form directly in the page - no database needed
const definition = {
  title: "Contact us", completeText: "Send message",
  elements: [
    { type: "text", name: "email", title: "Your email", inputType: "email", isRequired: true },
    { type: "comment", name: "message", title: "How can we help?", isRequired: true }
  ]
};
const survey = new Model(definition);
// Save after completion; SurveyJS offers a retry action if saving fails
survey.onComplete.add(async (sender, options) => {
  try {
    const response = await fetch("/api/responses", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ formId: "contact", data: sender.data })
    });
    const { id } = response.ok ? await response.json() : {};
    if (!Number.isInteger(id) || id < 1) throw new Error("Missing response ID");
    sender.setVariable("responseId", id);
    options.showSaveSuccess();
  } catch {
    options.showSaveError("We couldn't save your message. Please try again.");
  }
});
Server code
// POST /api/responses: Store submitted answers as one JSON document
app.MapPost("/api/responses", async (HttpRequest request, SurveyDb db) =>
{
    // Read the raw request body: binding to a class would drop unknown keys and re-format numbers such as 1.0
    if (await StoredJson.ReadBodyAsync(request) is not JsonObject body
        || body["formId"] is not JsonValue formId || body["data"] is not JsonNode data)
    {
        return Results.Json(new { error = "Expected { formId, data }" }, statusCode: 400);
    }

    var id = await StoredJson.InsertResponseAsync(db, formId.ToString(), data);   // Preserve float values such as 1.0

    return Results.Json(new { id }, statusCode: 201);
});

Live Example: Save Responses

Load JSON Schemas, Variables, and Answers

As your application grows, the same form may need to dynamically change, behave differently for different users, or open with answers already filled in. Your backend can provide the JSON schema, variables, and previous answers needed to prepare the form.

  • JSON schema
    Form JSON schema describes the questions, layout, and logic. You can include the schema in the page when the latter renders or fetch it from an endpoint before displaying the form. In either case, the server can dynamically adjust the schema for the current request.

  • Variables
    Variables provide context for the form. For example, the current user's name can appear in a title, and their subscription plan can control which questions are visible. Variables are excluded from the saved answers.

  • Previous answers
    If the user is returning to an existing record, also load its answers and assign them to survey.data. The form then opens with those values already filled in.

An endpoint can return all three pieces of data in one request.

Client code
import { Model } from "survey-core";

async function createSurvey(recordId) {
  if (window.FORM_DEFINITION) {
    // Option A: Use the schema and user variables embedded in the HTML response
    const survey = new Model(window.FORM_DEFINITION);
    survey.setVariables(window.FORM_VARIABLES);
    return survey;
  }
  // Option B: Load the definition, variables, and previous answers in one request
  const { definition, variables, data } =
    await fetch(`/api/forms/claim-request?record=${encodeURIComponent(recordId)}`).then(r => r.json());
  const survey = new Model(definition);
  survey.setVariables(variables);   // Variables are available in expressions such as {user.name} and are excluded from survey.data
  survey.data = data;               // Restore previously saved answers for editing
  return survey;
}
Server code
// Option A: Embed the schema and user variables in the HTML response
private void Embed()
{
    var path = Path.Combine(env.ContentRootPath, "shared", "definitions", "load-definition-variables-data.json");
    Definition = JsonNode.Parse(System.IO.File.ReadAllText(path));
    Variables = new { user = new { name = User.Identity?.Name, plan = User.FindFirstValue("plan") } };
}   // The page writes both with @Json.Serialize(), which escapes them for an inline script
// Option B: Return the definition, variables, and previous answers in one response
app.MapGet("/api/forms/{id}", async (string id, string? record, ClaimsPrincipal user, SurveyDb db) =>
{
    var definition = await db.Forms.Where(f => f.Key == id).Select(f => f.Json).SingleOrDefaultAsync();
    if (definition is null) return Results.Json(new { error = "Unknown form" }, statusCode: 404);

    var email = user.FindFirstValue(ClaimTypes.Email);
    long? recordId = long.TryParse(record, out var parsed) ? parsed : null;   // ?record= is empty for a new response
    var records = db.Responses.Where(r => r.Id == recordId);
    if (id == "claim-request")   // Only the signed-in customer's own claims
        records = records.Where(r => r.FormId == "claim" && SurveyDb.JsonValue(r.Data, "$.customer_email") == email);
    var data = recordId is null ? null : await records.Select(r => r.Data).SingleOrDefaultAsync();

    return Results.Json(new
    {
        definition = JsonNode.Parse(definition),                          // Return the stored form definition
        variables = new { user = new { name = user.Identity?.Name, plan = user.FindFirstValue("plan") } },
        data = data is null ? new JsonObject() : JsonNode.Parse(data),   // Return previous answers, or {} when none are available
    });
});

Live Example: Load JSON Schemas, Variables, and Answers

Resume Progress

With long forms, respondents may need to stop and return later. You can save their answers together with the form's UI state, which includes the current page and focused input field. Restoring both lets them continue from the same place.

While the respondent works, listen for answer and page changes and send the updated progress to the backend. Answer changes can happen on every keystroke, so wait for a short pause before saving. Send any pending changes when users close or reload the browser tab as well.

The backend should store one progress document for each user and form. When the respondent returns, load that document and restore the answers and UI state before they continue.

Client code
import debounce from "lodash/debounce";

const saveProgress = debounce(() => flushProgress().catch(showSaveError), 800);
function flushProgress() {
  saveProgress.cancel();
  if (pendingProgress === null) return saving ?? Promise.resolve();
  return saving ??= persistProgress().finally(() => { saving = null; });
}
function queueProgress() {
  if (!recording || locked) return;
  const body = JSON.stringify(snapshot());
  if (body === lastSnapshot) return;
  lastSnapshot = pendingProgress = body;
  setStatus("Changes will be saved automatically");
  saveProgress();
}
survey.onValueChanged.add(queueProgress);
survey.onUIStateChanged.add(queueProgress);   // Include page and focus changes
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden" && recording && !locked) {
    flushProgress().catch(showSaveError);
  }
});
Server code
// Return the current user's saved answers and UI state
app.MapGet("/api/progress/{formId}", async (string formId, ClaimsPrincipal user, SurveyDb db) =>
{
    if (user.FindFirstValue(ClaimTypes.NameIdentifier) is not { } userId)
        return Results.Json(new { error = "Sign in to load progress" }, statusCode: 401);
    var key = $"{userId}:{formId}";
    var json = await db.Progress.Where(p => p.Key == key).Select(p => p.Json).SingleOrDefaultAsync();

    return Results.Text(json ?? "null", "application/json");   // the draft as stored, or null when there is none
});

// Store progress under a key containing both the user ID and form ID
app.MapPut("/api/progress/{formId}", async (string formId, HttpRequest request, ClaimsPrincipal user, SurveyDb db) =>
{
    if (user.FindFirstValue(ClaimTypes.NameIdentifier) is not { } userId)
        return Results.Json(new { error = "Sign in to save progress" }, statusCode: 401);
    // Read the raw request body: binding to a class would drop unknown keys and re-format numbers in the stored JSON
    var progress = await StoredJson.ReadBodyAsync(request);
    await StoredJson.UpsertAsync(db, StoredTable.Progress, $"{userId}:{formId}", progress);   // Preserve float values such as 1.0

    return Results.NoContent();
});

Live Example: Resume Progress

Store Files Separately

A File Upload question can store file contents in the response as Base64 strings. This makes responses much larger. Alternatively, you can keep files in a separate storage. To do this, set the question's storeDataAsText property to false and handle the survey's onUploadFiles event.

The event handler should send selected files to an upload endpoint. The backend stores each file and returns its ID or URL. The form saves that reference in the answers, leaving the file contents out of the response document.

For private files, use IDs and a download endpoint that checks the user's access before returning a file. Handle the onDownloadFile event to retrieve the content when the form needs to display a preview.

Client code
// Upload: your server stores the files and returns an id (or a URL) for each
survey.onUploadFiles.add(async (_, options) => {
  const body = new FormData();
  options.files.forEach(file => body.append("files[]", file));   // "files[]": PHP keeps only the last of several "files"
  const response = await fetch("/api/files", { method: "POST", body }).catch(() => null);
  const ids = response?.ok ? await response.json().catch(() => null) : null;
  if (!Array.isArray(ids) || ids.length !== options.files.length || ids.some(id => typeof id !== "string" || !id)) {
    return options.callback([], ["Couldn't upload files. Please try again."]);
  }
  // The response stores these ids, not the file contents
  options.callback(options.files.map((file, i) => ({ file, content: ids[i] })));
});
Server code
// POST /api/files — store uploads, return their ids in the same order
app.MapPost("/api/files", async (IFormFileCollection form, SurveyDb db, RequestStorage storage, CancellationToken aborted) =>
{
    var files = form.GetFiles("files[]");                                  // field "files[]": one file or many
    if (files.Count == 0) return Results.Json(new { error = "Upload one or more files in a field named \"files[]\"" }, statusCode: 422);
    var uploads = new List<(string Id, string Name, byte[] Bytes, string Type)>();
    foreach (var file in files)                                             // check the whole batch before storing any of it
    {
        if (file.Length > 5 * 1024 * 1024) return Results.Json(new { error = "Each file must be 5 MB or less" }, statusCode: 422);
        var bytes = await FileType.ReadAllBytesAsync(file, aborted);
        if (FileType.Detect(bytes) is not { } type)                         // the detected type, never the client's
            return Results.Json(new { error = $"{file.FileName} is not a PNG, JPEG, WebP, GIF or PDF file" }, statusCode: 422);
        uploads.Add((Guid.NewGuid().ToString(), file.FileName, bytes, type));
    }
    foreach (var upload in uploads)                                         // named by id on disk, never by the client
    {
        await File.WriteAllBytesAsync(Path.Combine(storage.UploadsPath, upload.Id), upload.Bytes, aborted);
        db.Files.Add(new StoredFile { Id = upload.Id, Name = upload.Name, Type = upload.Type });
    }
    await db.SaveChangesAsync(aborted);
    return Results.Json(uploads.Select(upload => upload.Id));              // the ids, in upload order
}).DisableAntiforgery();   // called with fetch() from the same origin; with cookie auth, validate a token or use an Authorization header

Live Example: Store Files Separately

Load Choices from Web

Choice lists often come from data your application already stores, such as products or offices. Use the choicesByUrl property to load those options into a Dropdown, Checkboxes, or Radio Button Group question. The configured endpoint should return the list, and SurveyJS displays it as the question's choices.

The URL can include answers or variables in curly braces. For example, /api/offices?region={region} uses the selected region to request matching offices. When that answer changes, SurveyJS requests the list again.

The browser calls the URL directly. If an external service needs a secret key or does not allow cross-origin requests, have your backend call it and return the choices to the browser. If your own endpoint requires authentication headers, add them through settings.web.onBeforeRequestChoices.

Client code
// 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 code
// 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));
    }
});

Live Example: Load Choices from Web

Async Calculations and Validation

Some form logic needs information that only your backend has. For example, a validation rule may need to check whether an email address is already registered, or a calculation may need the shipping rate for a postcode.

Register an expression function with isAsync: true and have it request that information from your backend. The function returns a promise. When the request finishes, SurveyJS uses the result to update the calculation, validation rule, or visibility condition that called the function.

Client code
// Validate email availability using the backend's customer records
registerFunction({
  name: "emailExists",
  isAsync: true,
  func: async ([email]) => {
    const key = normalize("email", email);
    if (!key) return false;
    return lookup("email", key, `/api/customers/exists?email=${encodeURIComponent(key)}`, "exists");
  }
});

// Share one shipping lookup between the calculation and the postcode validator
registerFunction({
  name: "shippingCost",
  isAsync: true,
  func: async ([postcode]) => {
    const key = normalize("postcode", postcode);
    if (!key) return null;
    return lookup("postcode", key, `/api/shipping?postcode=${encodeURIComponent(key)}`, "price");
  }
});
Server code
// GET /api/customers/exists?email= — answers emailExists()
app.MapGet("/api/customers/exists", async (string? email, SurveyDb db) =>
{
    var normalized = (email ?? "").Trim().ToLowerInvariant();
    return new { exists = await db.Customers.AnyAsync(c => c.Email == normalized) };
});

// GET /api/shipping?postcode= — answers shippingCost(): the longest matching postcode prefix wins,
// { "price": null } when none matches (the form shows "We don't deliver to this postcode yet")
app.MapGet("/api/shipping", async (string? postcode, SurveyDb db) =>
{
    var code = (postcode ?? "").Replace(" ", "").ToUpperInvariant();
    // only a whole German (10115) or UK (SW1A 1AA) postcode gets a price, not anything that starts with a prefix
    if (!WholePostcode().IsMatch(code)) return new { price = (decimal?)null };
    var rates = await db.ShippingRates.ToListAsync();
    var rate = rates.Where(r => code.StartsWith(r.PostcodePrefix, StringComparison.Ordinal)).MaxBy(r => r.PostcodePrefix.Length);
    return new { price = rate?.Price };
});

Live Example: Async Calculations and Validation

Use Relational Storage

Storing each response as JSON is enough to preserve its answers. If you also need to query those answers with SQL or join them with other application data, copy the relevant values into database columns.

First, give the answers stable keys. A question's valueName sets the key it writes into the response independently of its question name. Form authors can then rename or move questions without breaking the mapping to your columns. If you need more mapping information, add a custom question property and expose it in Survey Creator's Property Grid.

When saving, keep the original JSON and the version of the form JSON schema used to collect it. Then copy the mapped values into their columns. Save both in one transaction, so the records stay consistent. Keeping the original document and schema version also lets you rebuild the mapping if your tables change later.

Client code
import { Model, Serializer } from "survey-core";

// Optional metadata describing the columns used by the server
Serializer.addProperty("question", { name: "dbColumn", category: "data" });

// Keep answer keys stable when question names change
const survey = new Model(definitions[definitionVersion]);
survey.completeText = "Submit claim";
Server code
// POST /api/claims — original JSON first, then the columns you query
app.MapPost("/api/claims", async (HttpRequest request, SurveyDb db) =>
{
    // Read the raw request body: binding to a class would drop unknown keys and re-format numbers in the stored JSON
    if (await StoredJson.ReadBodyAsync(request) is not JsonObject body
        || body["data"] is not JsonNode data || body["definitionVersion"] is not JsonValue version)
    {
        return Results.Json(new { error = "Expected { data, definitionVersion }" }, statusCode: 400);
    }

    await using var transaction = await db.Database.BeginTransactionAsync();
    var responseId = await StoredJson.InsertResponseAsync(db, "claim", data,   // the original, stored as it arrived: 1.0 stays 1.0
        definitionVersion: version.ToString());                               // keep the original and its version
    db.Claims.Add(new StoredClaim                                                 // keys come from valueName
    {
        ResponseId = responseId,
        CustomerEmail = (string?)data["customer_email"],
        Amount = (decimal?)data["amount"],
    });
    await db.SaveChangesAsync();
    await transaction.CommitAsync();

    return Results.Json(new { id = responseId }, statusCode: 201);
});

Live Example: Use Relational Storage

Fill Forms Together

Several people may need to fill out the same record, such as a dispatcher and a technician completing a job sheet. Participants see each other's answers, focus, and cursors.

To let participants fill out a form together, follow these steps:

  1. Add CollaborationPlugin from survey-core/collaboration to enable this functionality.
  2. Connect the clients to a WebSocket relay that groups participants by record. When someone joins, the relay sends the form JSON schema and current answers so that their form starts in the same state as everyone else's.
  3. Have the relay keep the latest value for each question and forward changes to the other clients. If two people change the same question, the last change wins.
  4. Save the completed response through the usual save endpoint.
Client code
// Transport the plugin's answer and presence messages over a WebSocket
function applySharedState(message) {
  const draft = survey?.data;
  const previousSession = sessionId;
  if (!collab) {
    survey = new Model(message.seed);
    survey.completeText = "Finish job sheet";
    collab = new CollaborationPlugin(survey, { getInviteLink: partnerLink });
    collab.onEvent.add((_, { message }) => {
      if (ready && responseId === null && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
    });
    survey.onComplete.add(completeJobSheet);
    mountSurvey(survey);
  }
  sessionId = message.sessionId;
  ready = true;
  collab.apply(message);
  // Restore the local draft if an empty session replaces the disconnected one
  if (previousSession && previousSession !== sessionId && !message.responseId && !message.peers.length) survey.data = draft;
  form.hidden = false;
  document.getElementById("collaboration-loading").hidden = true;
  setLocked(false);
  if (message.responseId) confirmCompletion(message.responseId, message.values);
}
Server code
// A WebSocket endpoint relays JSON between the people filling one record: answers, focus and cursors
app.Map("/ws/rooms/{recordId:regex(^[A-Za-z0-9_-]{{1,64}}$)}", async (string recordId, string? name, HttpContext context,
    FillRooms rooms, RequestStorage storage, ILogger<FillRoom> log) =>
{
    if (!context.WebSockets.IsWebSocketRequest) return Results.Json(new { error = "Expected a WebSocket request" }, statusCode: 400);
    // Demo only: the demo_user cookie stands in for your real session check here (may this user open this record?)
    if (context.User.Identity?.IsAuthenticated != true) return Results.Json(new { error = "Sign in to fill this record" }, statusCode: 403);
    var database = storage.DatabasePath;
    var room = await rooms.OpenAsync(RoomKey.For(storage, recordId), () => SeedAsync(database, recordId));   // the definition + the saved answers

    using var socket = await context.WebSockets.AcceptWebSocketAsync();
    await using var me = new Participant(socket, DisplayName(name, context.User.Identity.Name!));
    room.Join(me);
    me.Send(new
    {
        type = "init", clientId = me.Id, name = me.Name, colorIndex = FillRoom.ColorIndex(me.Slot), seed = room.Seed,
        values = room.Snapshot(), peers = room.Roster(me), sessionId = room.SessionId, responseId = room.ResponseId,
    });
    try
    {
        await foreach (var raw in me.ReceiveAsync(context.RequestAborted))
        {
            var message = Parse(raw);                                 // objects stay objects: {} is relayed as {}
            switch (Text(message?["type"]))
            {
                case "complete" when message!["data"] is JsonObject data:
                    await CompleteAsync(room, me, data, database, log);
                    break;
                case "value" when Text(message!["key"]) is { } key && room.ResponseId is null:
                    room.SetValue(key, message["value"]);              // last write wins
                    room.Broadcast(me, new { type = "value", from = me.Id, key, value = message["value"] });
                    break;
                case "presence" when message!["state"] is not null && raw.Length <= 4096:   // stamp identity, relay
                    var retain = message["retain"]?.GetValueKind() != JsonValueKind.False;
                    if (retain) me.State = message["state"];
                    room.Broadcast(me, new { type = "peer", retain, peer = FillRoom.Peer(me, message["state"]) }, droppable: !retain);
                    break;
            }                                                         // unknown types: ignore
        }
    }
    finally
    {
        room.Leave(me);                                               // peer-left; the room is dropped 2 s after the last person leaves
    }
    return Results.Empty;
});

Live Example: Fill Forms Together

Analyze Results with Dashboard

Once you have collected responses, use SurveyJS Dashboard to display and analyze them. Dashboard runs in the browser and uses the form JSON schema to choose a chart for each question automatically.

Load the JSON schema and request the saved responses for that form. The backend should return the answers as a JSON array, which the client passes to Dashboard along with the schema.

As the number of responses grows, you can filter or paginate them on the server. This lets users load the data they need without sending every stored response to the browser.

Client code
// Load answers with their submission dates for Dashboard's built-in date filter
async function loadResults(signal) {
  const query = new URLSearchParams({ formId: "feedback", includeCreatedAt: "1", limit: "5000" });
  const [definition, response] = await Promise.all([
    loadSchema(), fetch(`/api/responses?${query}`, { signal })
  ]);
  if (!response.ok) throw new Error("Responses load failed");
  const data = await response.json();
  if (!Array.isArray(data)) throw new Error("Invalid responses");
  return { definition, data: data.map(row => ({ ...row.data, createdAt: row.createdAt })) };
}

function renderResults(definition, data) {
  if (!dashboard) {
    const survey = new Model(definition);
    dashboard = new Dashboard({
      questions: survey.getAllQuestions(), data,
      dateFieldName: "createdAt", datePeriod: "last30days"
    });
    dashboard.render(container);
  } else {
    dashboard.updateData(data);
  }
}
Server code
// GET /api/responses?formId=&includeCreatedAt=&from=&to=&limit=&offset=
app.MapGet("/api/responses", async (string? formId, string? from, string? to, string? includeCreatedAt, int? limit, int? offset, SurveyDb db) =>
{
    var query = db.Responses.Where(r => r.FormId == formId
        && string.Compare(r.CreatedAt, from ?? "1970-01-01") >= 0);               // ISO-8601 UTC strings compare as dates
    if (!string.IsNullOrEmpty(to))
        query = query.Where(r => string.Compare(r.CreatedAt.Substring(0, 10), to) <= 0);   // up to and including that day
    var rows = await query.OrderBy(r => r.CreatedAt)
        .Skip(Math.Max(offset ?? 0, 0)).Take(Math.Clamp(limit ?? 500, 1, 5000))   // filter or page on the server for large volumes
        .Select(r => new { r.Data, r.CreatedAt }).ToListAsync();

    // Include submission dates separately when requested by Dashboard
    if (includeCreatedAt is "1" or "true")
        return Results.Json(rows.Select(r => new { data = JsonNode.Parse(r.Data), createdAt = r.CreatedAt }));

    return Results.Text("[" + string.Join(",", rows.Select(r => r.Data)) + "]", "application/json");   // documents as stored, not re-encoded
});

Live Example: Analyze Results with Dashboard

Edit Forms in Survey Creator

Survey Creator lets authors build and edit forms in your application. It works with the same form JSON schemas that Form Library displays to respondents. Your backend should load those schemas when the editor opens and save them when an author makes changes.

Load and Save Form JSON Schemas

Start by loading the saved schema into Survey Creator. You can use the same endpoint that supplies the schema to Form Library.

When the author clicks Save, Survey Creator calls saveSurveyFunc. Use this function to send the updated JSON schema to your backend. The backend should check the author's permission to edit forms, store the JSON, and confirm that it was saved. The next time a respondent opens the form, Form Library loads the updated JSON schema.

To save after each change, set the autoSaveEnabled property to true. Survey Creator then calls the same save function automatically. If the backend rejects a save, the backend should report the failure to Survey Creator so that the author can see it.

Client code
const creator = new SurveyCreator({ showTranslationTab: true });
// Queue writes so an older request cannot overwrite newer edits
const saver = createSchemaSaver(() => creator.JSON, async json => {
  const response = await fetch(`/api/forms/${formId}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: json
  });
  if ([401, 403].includes(response.status)) saveDenied = true;
  if (!response.ok) throw await responseError(response, "Couldn't save the form schema. Please try again.");
}, updateSaveState);
creator.saveSurveyFunc = (saveNo, callback) => {
  saver.save().then(saved => {
    callback(saveNo, saved);
    // Creator says "not saved" in the callback; show the server's reason after it
    if (!saved) creator.notify(saver.error, "error");
  });
};
Server code
// PUT /api/forms/{id} — store the definition as-is: it's one JSON document
app.MapPut("/api/forms/{id}", async (string id, HttpRequest request, ClaimsPrincipal user, IAuthorizationService auth, SurveyDb db) =>
{
    var allowed = await auth.AuthorizeAsync(user, "edit-forms");   // editing is an admin action: 403 otherwise
    if (!allowed.Succeeded)
        return Results.Json(new { error = allowed.Failure?.FailureReasons.FirstOrDefault()?.Message }, statusCode: 403);
    // The raw body, not a bound class: binding would drop the keys the class doesn't know and re-format numbers
    var definition = await StoredJson.ReadBodyAsync(request);
    await StoredJson.UpsertAsync(db, StoredTable.Forms, id, definition);   // stored as it arrived: 1.0 stays 1.0

    return Results.NoContent();   // the next page load renders the new version
});

Live Example: Load and Save Form JSON Schemas

Upload Files

Authors may need to add a logo, image, or file to a form. You can keep these files in your storage and save their URLs in the JSON schema to keep it small.

When an author selects a file, Survey Creator raises the onUploadFile event. Handle it by sending the file to your upload endpoint, then pass the returned URL back to Survey Creator. Survey Creator adds the URL to the JSON schema, and the next save preserves that reference.

You can reuse the storage endpoint for respondent uploads. If the file is private, its URL should point to a download endpoint that checks access before serving the file.

Client code
// Store each uploaded image separately and keep its URL in the form schema
creator.onUploadFile.add(async (_, options) => {
  const label = options.propertyName === "logo" || options.elementType === "header" ? "Logo" : "Image";
  uploads++; updateControls();
  showError("");
  try {
    if (!options.files.length || options.files.some(file =>
      file.size > 5242880 || !["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)))
      throw new Error("Choose a PNG, JPEG, WebP, or GIF image up to 5 MB.");
    const body = new FormData();
    options.files.forEach(file => body.append("files[]", file));
    const response = await fetch("/api/files", { method: "POST", body });
    const ids = response.ok ? await response.json() : null;
    if (!Array.isArray(ids) || ids.length !== options.files.length ||
      ids.some(id => typeof id !== "string" || !id))
      throw new Error(`Couldn't upload the ${label.toLowerCase()}. Please try again.`);
    options.callback("success", `/api/files/${encodeURIComponent(ids[0])}`);
    note(`${label} uploaded.`, "ok");
  } catch (error) {
    options.callback("error");
    showError(error.message);
    note(error.message, "error");
  } finally { uploads--; updateControls(); }
});
Server code
// POST /api/files — store uploads, return their ids in the same order
app.MapPost("/api/files", async (IFormFileCollection form, SurveyDb db, RequestStorage storage, CancellationToken aborted) =>
{
    var files = form.GetFiles("files[]");                                  // field "files[]": one file or many
    if (files.Count == 0) return Results.Json(new { error = "Upload one or more files in a field named \"files[]\"" }, statusCode: 422);
    var uploads = new List<(string Id, string Name, byte[] Bytes, string Type)>();
    foreach (var file in files)                                             // check the whole batch before storing any of it
    {
        if (file.Length > 5 * 1024 * 1024) return Results.Json(new { error = "Each file must be 5 MB or less" }, statusCode: 422);
        var bytes = await FileType.ReadAllBytesAsync(file, aborted);
        if (FileType.Detect(bytes) is not { } type)                         // the detected type, never the client's
            return Results.Json(new { error = $"{file.FileName} is not a PNG, JPEG, WebP, GIF or PDF file" }, statusCode: 422);
        uploads.Add((Guid.NewGuid().ToString(), file.FileName, bytes, type));
    }
    foreach (var upload in uploads)                                         // named by id on disk, never by the client
    {
        await File.WriteAllBytesAsync(Path.Combine(storage.UploadsPath, upload.Id), upload.Bytes, aborted);
        db.Files.Add(new StoredFile { Id = upload.Id, Name = upload.Name, Type = upload.Type });
    }
    await db.SaveChangesAsync(aborted);
    return Results.Json(uploads.Select(upload => upload.Id));              // the ids, in upload order
}).DisableAntiforgery();   // called with fetch() from the same origin; with cookie auth, validate a token or use an Authorization header

Live Example: Upload Files

Translate with AI

For multilingual forms, you can integrate AI in Survey Creator's Translations tab so that authors can translate titles, choices, and other form text semi-automatically.

When an author requests a translation, send the source strings and language information to your backend. The backend should call the AI provider you choose and return the translated strings in their original order. Keep the provider's API key on the server.

Authors can review and edit the translations in the UI before using them in the form.

Client code
// Return translated strings in the original order, and always finish the callback
creator.onMachineTranslate.add(async (_, options) => {
  showError("");
  try {
    const response = await fetch("/api/translate", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ strings: options.strings, from: options.fromLocale, to: options.toLocale })
    });
    if (!response.ok) throw await responseError(response, "AI translation failed. Please try again.");
    const strings = await response.json();
    if (!Array.isArray(strings) || strings.length !== options.strings.length || strings.some(text => typeof text !== "string"))
      throw new Error("The translation provider returned an invalid result. Please try again.");
    options.callback(strings);
  } catch (error) {
    options.callback([]);
    showError(`${translationError(error)} Existing translations are kept.`);
    note(error.message, "error");
  }
});
Server code
// POST /api/translate — strings in, translated strings out (same order); nothing goes to SurveyJS
app.MapPost("/api/translate", async (TranslateRequest body, AiTranslationClient ai, IOptions<SurveyJsOptions> options, CancellationToken aborted) =>
{
    if (string.IsNullOrEmpty(options.Value.AiApiKey))
        return Results.Json(new { error = "Set AI_API_KEY to enable translation" }, statusCode: 501);

    var translated = await ai.TranslateAsync(body.Strings, body.From, body.To, aborted);   // any OpenAI-compatible provider: your key, your choice
    if (translated is not JsonArray list || list.Count != body.Strings.Count || list.Any(s => s?.GetValueKind() != JsonValueKind.String))
        return Results.Json(new { error = "The AI provider returned an unexpected answer" }, statusCode: 502);

    return Results.Json(list);   // what options.callback() takes
});

Live Example: Translate with AI

Variable Presets

Form logic may depend on variables supplied by your application, such as a customer's subscription plan. Authors need sample values to test that logic before the form is used. Variable presets allow them to do that by providing named sets of those values in Survey Creator.

Load the saved presets from the backend when the editor opens. In the Preview tab, an author can select a preset to see how the form behaves with its values. Switching presets updates the preview using data already loaded in the browser.

When an author edits a preset, you need to save the updated presets to your backend as a JSON document. Check editing permission before saving, just as you do for form JSON schemas.

Client code
const creator = new SurveyCreator({
  variablePresets: {
    definition: {
      elements: [{
        type: "dropdown", name: "customerTier", title: "Customer plan",
        choices: [{ value: "basic", text: "Basic" }, { value: "premium", text: "Premium" }],
        isRequired: true
      }]
    },
    presets: []
  }
});
creator.onVariablePresetsChanged.add((_, options) => {
  // Switching scenarios changes only Preview; editing persists the preset list
  if (loaded && options.reason === "edit") { saver.changed(); saver.save(); }
});
Server code
// GET /api/variable-presets/{formId} — return the stored preset list, or [] when none are saved
app.MapGet("/api/variable-presets/{formId}", async (string formId, SurveyDb db) =>
{
    var json = await db.VariablePresets.Where(p => p.Key == formId).Select(p => p.Json).SingleOrDefaultAsync();
    return Results.Text(json ?? "[]", "application/json");
});

// PUT /api/variable-presets/{formId} — store the variable presets as-is: it's one JSON document
app.MapPut("/api/variable-presets/{formId}", async (string formId, HttpRequest request, ClaimsPrincipal user, IAuthorizationService auth, SurveyDb db) =>
{
    var allowed = await auth.AuthorizeAsync(user, "edit-forms");   // editing is an admin action: 403 otherwise
    if (!allowed.Succeeded)
        return Results.Json(new { error = allowed.Failure?.FailureReasons.FirstOrDefault()?.Message }, statusCode: 403);
    // The raw body, not a bound class: binding would drop the keys the class doesn't know and re-format numbers
    var presets = await StoredJson.ReadBodyAsync(request);
    await StoredJson.UpsertAsync(db, StoredTable.VariablePresets, formId, presets);   // stored as it arrived: 1.0 stays 1.0

    return Results.NoContent();
});

Live Example: Variable Presets

Edit Forms Together

Several authors can work on the same form. Participants see each other's edits, selection, and cursors, and cannot edit survey elements that another participant is editing.

To let several authors work on the same form, follow these steps:

  1. Add CollaborationPlugin from survey-creator-core/collaboration to enable this functionality.
  2. Connect the clients to a WebSocket relay. Have the relay add each edit to a change log as a JSON record and forward it to the other participants.
  3. When someone joins, send them the starting JSON schema and the change log. Applying those changes brings the new participant's editor up to date.
  4. Save the JSON schema through saveSurveyFunc and your usual save endpoint. After the collaboration session ends, the next session starts from the saved schema.
Client code
// Rebuild the shared form from its saved schema and ordered edit log
function initialize(message) {
  creator?.dispose();
  creator = new SurveyCreator({ showTranslationTab: true });
  creator.JSON = message.seed;
  collab = new CollaborationPlugin(creator, { roomId: formId, getInviteLink: sharedFormLink });
  creator.addPlugin("collaboration", collab);
  collab.setClientId(message.clientId);
  configureSaving();
  saver.markSaved();
  if (message.log.length) collab.apply(message.log);
  const append = (_, { record }) => send({ type: "append", payload: record });
  collab.onRecordAdded.add(append);
  collab.onRecordChanged.add(append);
  collab.onStateChanged.add(() => send({ type: "presence", state: collab.getState() }));
}
Server code
// The same kind of relay as Fill Forms Together, keeping an append-only log instead of a value map:
// Creator records must be replayed in order
app.Map("/ws/forms/{formId:regex(^[A-Za-z0-9_-]{{1,64}}$)}", async (string formId, string? name, HttpContext context,
    IAuthorizationService auth, EditRooms rooms, RequestStorage storage) =>
{
    if (!context.WebSockets.IsWebSocketRequest) return Results.Json(new { error = "Expected a WebSocket request" }, statusCode: 400);
    // Demo only: the demo_user cookie stands in for your real session check here. Editing is for editors (edit-forms)
    if (!(await auth.AuthorizeAsync(context.User, "edit-forms")).Succeeded)
        return Results.Json(new { error = "You don't have editor rights: only editors can change forms" }, statusCode: 403);
    var database = storage.DatabasePath;
    var room = await rooms.OpenAsync(RoomKey.For(storage, formId), () => SavedDefinitionAsync(database, formId));   // seed = saved definition

    using var socket = await context.WebSockets.AcceptWebSocketAsync();
    await using var me = new Participant(socket, DisplayName(name, context.User.Identity!.Name!));
    room.Join(me);
    me.Send(new { type = "init", clientId = me.Id, colorIndex = me.Slot, color = EditRoom.Palette[me.Slot], seed = room.Seed, log = room.Log() });
    if (room.Roster(me) is { Count: > 0 } peers) me.Send(new { type = "presence-sync", peers });
    try
    {
        await foreach (var raw in me.ReceiveAsync(context.RequestAborted))
        {
            var message = Parse(raw);                                 // records stay opaque: {} is relayed as {}
            switch (message?["type"] is JsonValue type && type.TryGetValue(out string? kind) ? kind : null)
            {
                case "append" when message!["payload"] is not null:  // append, then fan out
                    room.Append(me, message["payload"]);
                    break;
                case "presence" when message!["state"] is not null && raw.Length <= 4096:
                    me.State = message["state"];
                    room.Broadcast(me, new { type = "presence", peer = EditRoom.Peer(me) });
                    break;
            }                                                         // unknown types: ignore
        }
    }
    finally
    {
        room.Leave(me);                                               // presence-leave; the log lives until the room empties
    }
    return Results.Empty;
});

Live Example: Edit Forms Together

Run Server-Side Workflows

Some workflows need SurveyJS logic on the server. You may need to check a submission before storing it, find problems in a form JSON schema, create a PDF, or read answers from a document.

These operations run in Node.js. A Node.js backend can run the components directly; other backends can call a Node.js service over HTTP. In either case, your backend supplies the required data and uses the result in its own workflow.

Validate Responses

Browser validation helps respondents correct their answers while filling out a form. Your API can also receive requests that bypass the form, so you need to repeat validation on the server before storing a response.

When a submission arrives, load the form JSON schema from your storage. Validate the submitted answers against that schema on the server, checking required questions, value types, and allowed choices.

Save the response only if validation succeeds. If it fails, return the errors to the client so that the respondent can correct the answers.

Client code
// Confirm a save only after the backend accepts the answers and returns a response ID
survey.onComplete.add(async (sender, options) => {
  lock(true);
  sender.completedHtml = "<h3>Submitting your claim...</h3>";
  options.showSaveInProgress();
  try {
    const result = await submit(sender.data);
    if (result.rejected) throw new Error(result.errors.map(describe).join("; "));
    sender.completedHtml = `<h3>Your claim has been saved.</h3><p>Response ID: ${result.id}</p>`;
    options.showSaveSuccess();
  } catch (error) {
    sender.completedHtml = "<h3>Your claim hasn't been saved.</h3>";
    const message = error instanceof TypeError ? "Couldn't validate the response. Please try again." : error.message;
    options.showSaveError(message);
  } finally { lock(false); }
});
Server code
// POST /api/responses — ask the SurveyJS service to validate, then store as usual
app.MapPost("/api/responses", async (HttpRequest request, SurveyDb db, SurveyJsService service) =>
{
    // The raw body keeps {} as {} and 1.0 as 1.0 (see Save Responses)
    if (await StoredJson.ReadBodyAsync(request) is not JsonObject body || body["data"] is not JsonObject data
        || body["formId"] is not JsonValue formIdValue || !formIdValue.TryGetValue(out string? formId))
        return Results.Json(new { error = "Expected { formId, data } with an answers object" }, statusCode: 400);
    var definition = await db.Forms.Where(f => f.Key == formId).Select(f => f.Json).SingleOrDefaultAsync();
    if (definition is null) return Results.Json(new { error = "Unknown form" }, statusCode: 404);

    var check = await service.PostAsync("/response", new { schema = JsonNode.Parse(definition), response = data }, TimeSpan.FromSeconds(10));
    if (check is { Status: 422, Object: { } found } && found["errors"] is not null && !found.ContainsKey("warnings"))
        return Results.Json(new { errors = found["errors"] }, statusCode: 400);   // the answers don't fit the definition
    if (check is not { Status: 200, Object.Count: 0 })                           // fail closed: only exactly {} means valid
        throw service.Unexpected("/response", check, check is { Status: 422, Object: { } invalid } && invalid.ContainsKey("errors")
            && invalid.ContainsKey("warnings") ? "The stored definition has errors" : "SurveyJS service error");

    var id = await StoredJson.InsertResponseAsync(db, formId, data);              // stored as it arrived: 1.0 stays 1.0
    return Results.Json(new { id }, statusCode: 201);
});

Live Example: Validate Responses

Lint JSON Schemas

A form JSON schema can contain mistakes that stop its questions or logic from working as intended. For example, a condition may refer to a question that does not exist. Check JSON schemas using the SurveyJS Linter before saving and return its findings to Survey Creator so that authors can fix these problems before respondents encounter them.

Client code
// Display the server's errors and warnings and return the actual save result to Creator
async function saveDefinition(definition) {
  const response = await fetch(`/api/forms/${formId}`, {
    method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(definition)
  });
  const report = response.status === 204 ? {} : await response.json();
  reportFindings(report);
  if (response.status === 422 && Array.isArray(report.errors) && report.errors.length) {
    note("Form schema not saved. Fix the reported errors and retry.", "error");
    return false;
  }
  if (!response.ok) throw new Error(report.error || "Couldn't save the form schema. Please try again.");
  const count = report.warnings?.length ?? 0;
  note(count ? `Schema saved with ${count} warning${count === 1 ? "" : "s"}. Review the findings above.` : "Form schema saved successfully.", "ok");
  return true;
}
creator.saveSurveyFunc = async (saveNo, callback) => callback(saveNo, await checkAndSave(creator.JSON));
Server code
// PUT /api/forms/{id} — lint the definition from Creator before storing it
app.MapPut("/api/forms/{id}", async (string id, HttpRequest request, ClaimsPrincipal user, IAuthorizationService auth, SurveyDb db, SurveyJsService service) =>
{
    var allowed = await auth.AuthorizeAsync(user, "edit-forms");
    if (!allowed.Succeeded)
        return Results.Json(new { error = allowed.Failure?.FailureReasons.FirstOrDefault()?.Message }, statusCode: 403);
    var definition = await StoredJson.ReadBodyAsync(request);   // the raw body keeps {} as {} (see Load and Save Form JSON Schemas)

    var lint = await service.PostAsync("/schema", definition, TimeSpan.FromSeconds(10));
    if (lint is { Status: 422, Object: { } found } && found.ContainsKey("errors") && found.ContainsKey("warnings"))
        return Results.Text(lint.Text, "application/json", statusCode: 422);      // errors: refuse the save, report them as they are
    var warningsOnly = lint is { Status: 200, Object: { Count: 1 } answer } && answer.ContainsKey("warnings");
    if (!warningsOnly && lint is not { Status: 200, Object.Count: 0 })           // fail closed: nothing else counts as clean
        throw service.Unexpected("/schema", lint);
    await StoredJson.UpsertAsync(db, StoredTable.Forms, id, definition);         // stored as it arrived: 1.0 stays 1.0

    return warningsOnly ? Results.Json(new { warnings = lint.Object!["warnings"] }) : Results.NoContent();   // warnings don't block the save
});

Live Example: Lint JSON Schemas

Generate PDFs

A backend workflow may need a PDF for an archive or email attachment. SurveyJS PDF Generator can create the document on the server without opening a browser.

Load the form JSON schema and, for a completed form, its saved answers. Pass them to PDF Generator to create the document. Your backend can then store the PDF, attach it to an email, or send it to the browser with the application/pdf content type.

Client code
// Open a tab during the click and navigate only after the server returns a PDF
async function generatePdf(id, action) {
  if (urls.has(id)) return usePdfUrl(id, action, urls.get(id));
  const tab = action === "open" ? window.open("/examples/server-pdf/loading", "_blank") : null;
  try {
    const response = await fetch(`/api/claims/${id}/pdf`);
    if (!response.ok) throw await responseError(response, "Couldn't generate the PDF. Please try again.");
    if (!response.headers.get("content-type")?.startsWith("application/pdf")) throw new Error("The server didn't return a PDF. Please try again.");
    const blob = await response.blob();
    if (!blob.size) throw new Error("The server returned an empty PDF. Please try again.");
    const url = URL.createObjectURL(blob);
    urls.set(id, url);
    if (action === "download") return usePdfUrl(id, action, url);
    const opened = tab && !tab.closed;
    if (opened) tab.location = url;
    return { message: opened ? "PDF opened in a new tab." : "PDF ready. Select Open PDF again or Download PDF.", needsAction: !opened };
  } catch (error) { tab?.close(); throw error; }
}
Server code
// GET /api/claims/{id}/pdf — ask the SurveyJS service for the filled form and pass the PDF through
app.MapGet("/api/claims/{id:long}/pdf", async (long id, SurveyDb db, SurveyJsService service, IWebHostEnvironment env, HttpResponse response) =>
{
    var claim = await db.Responses.SingleOrDefaultAsync(r => r.FormId == "claim" && r.Id == id);
    if (claim is null) return Results.Json(new { error = "Unknown claim" }, statusCode: 404);
    // Use the schema version recorded with the response
    if (claim.DefinitionVersion is not (null or "v1" or "v2"))
        return Results.Json(new { error = "The schema version for this claim is unavailable" }, statusCode: 409);
    var definition = claim.DefinitionVersion is null
        ? await db.Forms.Where(f => f.Key == "claim").Select(f => f.Json).SingleAsync()
        : await File.ReadAllTextAsync(Path.Combine(env.ContentRootPath, "shared", "definitions", $"relational-storage.{claim.DefinitionVersion}.json"));

    var pdf = await service.PostAsync("/pdf", new { schema = JsonNode.Parse(definition), response = JsonNode.Parse(claim.Data) }, TimeSpan.FromSeconds(60));
    if (pdf.Status != 200 || !pdf.HasContentType("application/pdf") || !pdf.BodyStartsWith("%PDF-"))
        throw service.Unexpected("/pdf", pdf);

    response.Headers.ContentDisposition = $"inline; filename=\"claim-{id}.pdf\"";
    response.Headers.CacheControl = "private, no-store";
    return Results.Bytes(pdf.Body, "application/pdf");
});

Live Example: Generate PDFs

Extract Responses from Documents

Some responses arrive as completed paper forms, scans, or PDFs. AI Form Response Extractor can use your form JSON schema to read those documents and return answers in the same format as an online response.

Upload the document to your backend and send it, along with the JSON schema, to the extractor. The extractor calls the AI provider you configure and returns the answers with confidence information. It can also return a unique ID detected in the document, such as an ID from a QR code.

Use the returned answers to fill a draft form. Show which answers need checking so a person can review and correct them before submitting. Extraction itself does not save a response—save the reviewed answers through your usual endpoint.

Client code
// Extract a draft without saving it and validate the response before replacing any answers
async function extract(file, signal) {
  const body = new FormData();
  body.append("scan", file);
  const response = await fetch("/api/work-orders/extract", { method: "POST", body, signal });
  if (!response.ok) throw await responseError(response, "Couldn't extract the answers. Try again or enter the answers directly in the form.");
  const result = await response.json();
  if (!result.answers || typeof result.answers !== "object" || Array.isArray(result.answers) || !Array.isArray(result.confidence)) {
    throw new Error("The extraction result couldn't be read. Try again or enter the answers directly in the form.");
  }
  return result;
}
Server code
// POST /api/work-orders/extract — send the uploaded scan to the SurveyJS service; return a draft response
app.MapPost("/api/work-orders/extract", async (IFormFile? scan, SurveyDb db, SurveyJsService service, CancellationToken aborted) =>
{
    if (scan is null) return Results.Json(new { error = "Upload the scan in a field named \"scan\"" }, statusCode: 400);
    if (scan.Length > 5 * 1024 * 1024) return Results.Json(new { error = "The scan must be a file of 5 MB or less" }, statusCode: 413);
    var bytes = await FileType.ReadAllBytesAsync(scan, aborted);
    if (FileType.Detect(bytes) is null)                                       // its first bytes, not the client's content type
        return Results.Json(new { error = "The file is not a PDF, PNG, JPEG, WebP or GIF document" }, statusCode: 400);
    var definition = await db.Forms.Where(f => f.Key == "work-order").Select(f => f.Json).SingleAsync();
    var output = await service.PostAsync("/extract",                          // JSON with base64, not multipart
        new { schema = JsonNode.Parse(definition), document = Convert.ToBase64String(bytes) }, TimeSpan.FromSeconds(120));

    return output switch                                                      // nothing is saved: a person reviews the draft
    {
        { Status: 200, Object: { } result } when result["data"] is JsonObject data =>
            Results.Json(new { answers = data, confidence = result["confidence"] ?? new JsonArray(), uniqueId = result["uniqueId"] }),
        { Status: 400, Error: "INVALID_DOCUMENT" } => Results.Json(new { error = "The file is not a PDF, PNG, JPEG, WebP or GIF document" }, statusCode: 400),
        { Status: 503, Error: "AI_NOT_CONFIGURED" } => Results.Json(new { error = "The SurveyJS service has no AI provider configured" }, statusCode: 503),
        { Status: 502, Error: "EXTRACTION_FAILED" } => Results.Json(new { error = "Could not extract the response from the document" }, statusCode: 502),
        _ => throw service.Unexpected("/extract", output, logBody: false),
    };
}).DisableAntiforgery();   // called with fetch() from the same origin; with cookie auth, validate a token or use an Authorization header

Live Example: Extract Responses from Documents

Send feedback to the SurveyJS team

Need help? Visit our support page

Your cookie settings

We use cookies to make your browsing experience more convenient and personal. Some cookies are essential, while others help us analyse traffic. Your personal data and cookies may be used for ad personalization. By clicking “Accept All”, you consent to the use of all cookies as described in our Terms of Use and Privacy Statement. You can manage your preferences in “Cookie settings.”

Your renewal subscription expires soon.

Since the license is perpetual, you will still have permanent access to the product versions released within the first 12 month of the original purchase date.

If you wish to continue receiving technical support from our Help Desk specialists and maintain access to the latest product updates, make sure to renew your subscription by clicking the "Renew" button below.

Your renewal subscription has expired.

Since the license is perpetual, you will still have permanent access to the product versions released within the first 12 month of the original purchase date.

If you wish to continue receiving technical support from our Help Desk specialists and maintain access to the latest product updates, make sure to renew your subscription by clicking the "Renew" button below.