Getting started
This tutorial builds a contact form twice. First you run it headless, as a console program, to see how the controller validates and submits. Then you render the same schema in a Blazor app. It takes about ten minutes.
On this page
You declare a form from a C# class: FormSchema. describes the fields, and a FormController reads and writes their values as the types of your members, so a typo in a member name or a value of the wrong type is a compile error. Both steps below use that typed API. A form that is only known at runtime, for example one stored as JSON, uses the runtime mode instead.
Check the prerequisites first: the .NET 11 SDK, and for the components a Blazor app with Klyroo.UI set up.
1. Run a form without a UI
Create a console project and add the engine package:
dotnet new console -n ContactForm
cd ContactForm
dotnet add package Klyroo.Form.Core --prereleaseReplace Program. with a model, a schema and a controller:
using Klyroo.Form;public sealed class Contact
{
public string Name { get; set; } = "";
public string Email { get; set; } = "";
public Topic Topic { get; set; }
public string? Message { get; set; }
}
public enum Topic { Sales, Support }var schema = FormSchema.For<Contact>(s =>
{
s.FormKey = "contact";
s.Field(c => c.Name, f => f.Required());
s.Field(c => c.Email, f => f.Required().Rule(e => e.Contains('@'), "Enter a valid email address"));
});
var name = schema.Field(c => c.Name);
var email = schema.Field(c => c.Email);
var form = new FormController<Contact>(schema);
form.Set(name, "Alice", markTouched: true);
form.Set(email, "alice", markTouched: true);
Console.WriteLine(form.GetError(email)); // Enter a valid email address
Console.WriteLine(await form.SubmitAsync()); // False
form.Set(email, "alice@example.com");
Console.WriteLine(await form.SubmitAsync((contact, ct) =>
{
Console.WriteLine($"Send a reply to {contact.Email}");
return Task.FromResult(true);
})); // True
Console.WriteLine(form.IsDirty); // FalseRun it with dotnet run. The output is:
Enter a valid email address
False
Send a reply to alice@example.com
True
FalseWhat happened:
FormSchema.declares one field per member you name.For <Contact> s.returns a handle,Field (c => c. Email, ...) FormField, which carries the type of the value. The schema is immutable and holds no state, so you can keep it in a static member and share it.<Contact, string> Setstores a value through its handle.markmarks the field as touched, and only touched fields show their error, soTouched: true GetErrorreturns the message. A field that the user has not interacted with stays quiet until you call(email) Validate()or submit.SubmitAsyncvalidates every field. The first submit fails because the email has no@, so the save step does not run. The second passes validation, writes the values into a newContact, calls your save step with it, and returnstrue.- After a successful submit the controller takes a new snapshot of the values, so
IsDirtyisfalseagain.
The Klyroo. package has no UI dependency. The rest of this tutorial uses the same schema in Blazor.
2. Add Klyroo.Form to a Blazor app
Use a Blazor Web App with Interactive Server, WebAssembly or Auto rendering, or a .NET MAUI Blazor Hybrid app. Add the package to the project that hosts the components:
dotnet add package Klyroo.Form --prereleaseThe package builds on Klyroo.UI and brings it in as a dependency.
Register the services
Call AddKlyrooForm() in Program.. It registers FormService and Dynamic and calls AddKlyrooUi():
using Klyroo.Form;
builder.Services.AddKlyrooForm();With Interactive WebAssembly or Auto, call it in the server project and in the . project, because components run in both.
Import the namespace
In _:
@using Klyroo.FormLoad the stylesheets
The components use the theme tokens of Klyroo.UI and classes that this package ships precompiled. In App., inside <head>:
<link rel="stylesheet" href="@Assets["_content/Klyroo.UI/klyroo.preflight.css"]" />
<link rel="stylesheet" href="@Assets["_content/Klyroo.UI/klyroo.css"]" />
<link rel="stylesheet" href="@Assets["_content/Klyroo.Form/klyroo-form.css"]" />Klyroo.UI documents more setup options, such as color mode and fonts, in its repository. Without these three files the form renders unstyled.
3. Render the schema
Put the Contact class in your project, then create Components/. Api stands for your own service:
@page "/contact"
@rendermode InteractiveServer
@inject IContactApi Api
<KlyFormEngine TModel="Contact" Schema="_schema" Model="_contact" SubmitLabel="Send" OnSave="SaveAsync" OnSubmit="Sent" />
@if (_sentTo is not null)
{
<p>Thanks, we will write to @_sentTo.</p>
}
@code {
private readonly Contact _contact = new();
private string? _sentTo;
// Keep the schema in a field: a new instance makes the component start a new controller.
private static readonly FormSchema<Contact> _schema = FormSchema.For<Contact>(s =>
{
s.Title = "Contact us";
s.Field(c => c.Name, f => f.Required());
s.Field(c => c.Email, f => f.Required().Rule(e => e.Contains('@'), "Enter a valid email address"));
s.Field(c => c.Topic);
s.Field(c => c.Message, f => f.Required().AsTextarea().MaxLength(500));
});
private async Task<bool> SaveAsync(Contact contact, CancellationToken ct) => await Api.SendAsync(contact, ct);
private void Sent(Contact contact) => _sentTo = contact.Email;
}Run the app and open /. Press Send with the form empty: each required field shows This field is required. Type alice in the email field and leave it: the field shows the email message. Fill every field correctly and press Send: SaveAsync receives the Contact the form wrote its values into, and the confirmation appears.
Four details to know:
@rendermode Interactiveis needed unless your app already renders interactively everywhere. In Static SSR the form appears but does not react to input.Server - Keep the schema in a field or a static member.
KlyFormEnginecreates a new controller whenever it receives a different<TModel> FormSchemainstance, which would discard what the user typed if the schema were built inline in the markup.<TModel> - Razor infers
TModelfromSchema,Model,FormorOnSave, so the markup usually names no type. A method given toOnSubmitstops the inference with a conversion error, so this page writesTModel="Contact". A lambda or a boundEventCallbackhas the same effect.<Contact> OnSaveruns after validation and the schema hooks succeed, while the form shows its saving state, and returnstrueon success.OnSubmitis raised afterwards with the same model, once the form is clean, so it is the place to navigate. See Save from the component.
The form writes the values into _ when it submits, all or nothing: if validation, a hook or OnSave fails, the model keeps its previous values, and members the form does not show keep what they had. Pass no Model and every submit creates a new Contact.
4. Read the rules from attributes
If your model already carries DataAnnotations attributes, add the extra package and let the schema read them:
dotnet add package Klyroo.Form.DataAnnotations --prereleasevar schema = FormSchema.For<Contact>(s => s.FromDataAnnotations());[Required], [StringLength], [Range], [EmailAddress], [Display] and the other attributes become the same rules you wrote by hand above, and IValidatable runs at submit. The guides list which attribute becomes which rule.
Next steps
- Guides: declare a form from a model, validate against the server, build a wizard, open a form in a dialog, test your forms.
- Concepts: how the schema, the controller and the components fit together.
- Platforms: render modes, .NET MAUI Blazor Hybrid and NativeAOT.
- Forms defined at runtime: the dictionary-based mode, for forms stored as data.
- API reference: every public type and member.