In the SharpRune app for iPhone and iPad, tap Run in Preview: the app compiles the Razor components on the device and runs the project on .NET 9. On a computer, download the project and run it with the .NET 9 SDK. The separate C# companion practice below runs in this browser.
The two directions of @bind
- Render: field to box
@bind="cups"writescupsinto the element'svalue - You edit, and
onchangefireswhen you leave the box, or on every key with@bind:event="oninput" - The text is parsed to the field's type
"12"stores 12; an empty box storesdefault, socups = 0 - If parsing fails, nothing is stored
"two"in the text box:cupsstays 3 and the box reverts - Stored; any
@bind:afterruns, then a renderevery expression that readscupsshows the new value
Number and date inputs parse with the invariant culture, text boxes with the current culture or @bind:culture. Use @bind:get and @bind:set when your code decides what is stored.
What @bind turns into
@bind is shorthand that the Razor compiler expands into two parts. For <input @bind="name" />, it writes a value attribute that holds the field formatted as a string, and it attaches an onchange handler. The handler receives the element's new value as a string, converts it to the field's type and assigns it. Because the handler is an ordinary Blazor event, the component renders afterwards, so everything that reads the field updates. That is the whole loop of two-way binding: field to element on render, element to field on the event.
The attribute and event depend on the element. A text box binds value with the change event, which fires when the box loses focus or you press Enter. A checkbox binds checked to a bool. A select binds the selected option's value; with an enum field, the option values are enum names and Blazor parses them back. @bind:event="oninput" switches to the input event, which fires on every keystroke. The note box in this project uses it, so its character count follows your typing, while the name updates only when you leave its box.
@bind:after, @bind:get and @bind:set
@bind:after names a method that runs after the new value has been assigned. The cup size select uses it to call CheckStockAsync, which reads the new size, waits briefly and writes a message. The method may return Task, and Blazor renders when it first awaits and again when it finishes, as for an async event handler. An EventCallback is not supported as the @bind:after target; pass a method or a lambda.
@bind:get and @bind:set split the two directions. @bind:get supplies the value to show, and @bind:set receives the user's value instead of a direct assignment. The voucher box uses them with oninput. SetVoucher keeps letters and digits, converts them to upper case and stops at eight characters. Blazor then renders the stored value back into the box, so typing coffee 10! leaves COFFEE10 on screen. The older pattern of value="@voucher" plus an @oninput handler binds one way only: the handler can change the field, but the box keeps whatever the user typed. @bind:get needs a matching @bind:set (error RZ10015), and @bind cannot be combined with @bind:get on the same element (error RZ10018).
Parsing, formatting and culture
When the field is not a string, Blazor converts in both directions. For an int it parses the text as a number; for a DateOnly or DateTime it parses a date. The culture depends on the element. Inputs of type number and date use the invariant culture, because browsers send their values in a fixed form: digits with a dot for numbers, and yyyy-MM-dd for dates. Text boxes use CultureInfo.CurrentCulture. SharpRune's Preview runs the app with invariant globalization, so the current culture there is the invariant one, and the order card says so. On a computer, the current culture usually follows the browser's language, so the same text box might expect a comma as the decimal separator. @bind:culture fixes the culture for one element when you need a stable rule.
@bind:format sets a format string for dates. The second pickup box uses dd.MM.yyyy, which controls how the date is written and the exact pattern typed text must match: 24.12.2026 is accepted, while 1.12.2026 is not, because the pattern needs a two-digit day. Do not add @bind:format to an input of type date; Blazor already uses the yyyy-MM-dd form the browser expects. Number formats such as currency are not available through @bind:format, which is why the order card formats the total itself with ToString("0.00").
Input that does not parse, and empty input
If the text cannot be converted, Blazor does not assign the field. It does record what the browser sent, so on the next render it sees that the element no longer matches the field and writes the field's value back. The visible effect is that the box reverts to the last good value. Type two into the second cups box and leave it, and the box shows the previous number. 2.5 is rejected the same way, because an int cannot hold the fraction. With @bind:event="oninput" the revert happens after every keystroke, so some partial input cannot be typed at all.
An empty box is the exception. When the browser sends an empty string, Blazor assigns default(T): 0 for an int, null for an int?, and 0001-01-01 for a DateOnly. Clearing a cups box therefore sets cups to 0 and the total to 0.00. When empty must mean not entered, bind to a nullable type such as int? or DateOnly? and handle null in your code. For forms that should show error messages instead of reverting quietly, EditForm with input components such as InputNumber and InputDate records invalid input as validation errors.
Trace the coffee order
Start in the first card. Typing Ann into the name box changes nothing below until you leave the box; the change event then assigns name and Home renders. Typing into the note box assigns note on every input event, so the character count follows each key. Choose Large in the select: @bind stores CupSize.Large, then CheckStockAsync runs, the first render shows Checking Large cups… and the final one shows the stock message with the new price, 3.60.
In the numbers card, both cups boxes are bound to the same field, so changing one changes the other on the next render. Type two into the text box and leave it: the conversion fails, the field keeps its old value, and the render writes it back. The two pickup boxes share one DateOnly field as well. The picker sends 2026-12-24 in invariant form, and the text box shows the same date as 24.12.2026. The console companion runs these conversions on fixed inputs and prints stored, reverted or the default for each one, plus two order totals. It agrees with the app on these cases, but it calls int.TryParse and DateOnly.TryParseExact directly instead of Blazor's converter.
Common mistakes, practice and review
Common mistakes: expecting a text box with plain @bind to update while you type; binding a non-nullable number and treating 0 as not entered; parsing decimals in a text box with the invariant culture, where a comma is a group separator, so 1,5 becomes 15; and hiding logic in a property setter used by @bind when @bind:set or @bind:after would state the intent. The @bind attributes are also case-sensitive, so @Bind does not work.
To practice, change cups to int? and show "How many cups?" when it is null. Add a decimal tip in a text box with @bind:culture="CultureInfo.InvariantCulture", then type 1.5 and 1,5 and compare the results. Move the stock check from @bind:after into a @bind:get/@bind:set pair and compare the two versions. Add a DateOnly? field for a second pickup date and handle an empty box.
@bindwrites the field into the element on render and reads it back on change, or on every keystroke with@bind:event="oninput".@bind:afterruns code after the value is stored;@bind:getand@bind:setlet your setter decide what is stored.Numberand date inputs use the invariant culture; text boxes use the current culture or@bind:culture.- Text that does not parse reverts to the last good value, and an empty box stores default(T).
Two-way binding — Blazor WebAssembly project
Run the project
- Tap Run in Preview. SharpRune copies these files into a new project, compiles the Razor components on this device and opens the app in Preview.
- Type in the name box and in the note box and compare when the text below updates. Change the cup size and tick Oat milk.
- Type two into the second cups box and leave it, type 31.02.2026 into the date text box, and type coffee 10! into the voucher box.
- Change a .razor file and tap Run again to rebuild.
- On a computer: install the .NET 9 SDK, save the files with their folders, and run dotnet run in that folder.
Project files
TwoWayBinding.csproj
Download file ↗<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>TwoWayBinding</AssemblyName>
<RootNamespace>TwoWayBinding</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
</ItemGroup>
</Project>
Program.cs
Download file ↗using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using TwoWayBinding;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
// <App> replaces <div id="app"> in wwwroot/index.html.
builder.RootComponents.Add<App>("#app");
// HeadOutlet lets <PageTitle> set the browser tab title.
builder.RootComponents.Add<HeadOutlet>("head::after");
await builder.Build().RunAsync();
App.razor
Download file ↗<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<h1>Not found</h1>
<p>There is no page at this address.</p>
</NotFound>
</Router>
_Imports.razor
Download file ↗@using System.Globalization
@using System.Net.Http
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using TwoWayBinding
Pages/Home.razor
Download file ↗@page "/"
<PageTitle>Coffee order</PageTitle>
<h1>Coffee order</h1>
<section class="card">
<h2>When the value is copied</h2>
@* Default @bind: the field changes on the change event, when you leave the box. *@
<label>Name (copied when you leave the box)
<input @bind="name" />
</label>
@* @bind:event="oninput": the field changes on every keystroke. *@
<label>Note for the barista (copied on every key)
<input @bind="note" @bind:event="oninput" />
</label>
<p>Name: <strong>@name</strong></p>
<p>Note: <strong>@note</strong> <span class="muted">(@note.Length characters)</span></p>
</section>
<section class="card">
<h2>Select and checkbox</h2>
@* A select binds its value. @bind:after runs after the new value is stored in size. *@
<label>Cup size
<select @bind="size" @bind:after="CheckStockAsync">
@foreach (var option in Enum.GetValues<CupSize>())
{
<option value="@option">@option</option>
}
</select>
</label>
<p class="muted">@stockMessage</p>
@* A checkbox binds its checked state to a bool. *@
<label class="check"><input type="checkbox" @bind="oatMilk" /> Oat milk (+0.40)</label>
</section>
<section class="card">
<h2>Numbers and dates</h2>
@* type="number" and type="date" always use the invariant culture. *@
<label>Cups (number field)
<input type="number" min="1" max="20" @bind="cups" />
</label>
@* A text box bound to an int: text that does not parse is replaced by the last good value.
An empty box is different: Blazor stores default(int), which is 0. *@
<label>Cups again (text box: try "two" or "2.5", then leave the box)
<input @bind="cups" />
</label>
<label>Pickup date (date picker)
<input type="date" @bind="pickup" />
</label>
@* @bind:format controls how the date is written and the exact pattern it must match. *@
<label>Pickup date again (text box, dd.MM.yyyy)
<input @bind="pickup" @bind:format="dd.MM.yyyy" />
</label>
</section>
<section class="card">
<h2>Your own get and set</h2>
@* @bind:get supplies the value, @bind:set receives what the user typed. The setter cleans it,
and Blazor writes the cleaned value back into the box. *@
<label>Voucher code (try coffee10)
<input @bind:get="voucher" @bind:set="SetVoucher" @bind:event="oninput" />
</label>
<p class="muted">@(VoucherApplied ? "COFFEE10 applied: 10% off." : "Letters and digits only, up to 8.")</p>
</section>
<section class="card summary">
<h2>Order</h2>
<p>@cups × @size@(oatMilk ? " with oat milk" : "") for @(string.IsNullOrWhiteSpace(name) ? "a guest" : name)</p>
<p>Pickup on @pickup.ToString("dddd, d MMMM yyyy", CultureInfo.InvariantCulture)</p>
<p>Total: <strong>@Total.ToString("0.00", CultureInfo.InvariantCulture)</strong></p>
<p class="muted">Current culture: @(CultureInfo.CurrentCulture.Name == "" ? "invariant" : CultureInfo.CurrentCulture.Name)</p>
</section>
@code {
private string name = "";
private string note = "";
private CupSize size = CupSize.Medium;
private bool oatMilk;
private int cups = 2;
private DateOnly pickup = DateOnly.FromDateTime(DateTime.Today.AddDays(1));
private string voucher = "";
private string stockMessage = "Change the size to run @bind:after.";
private bool VoucherApplied => voucher == "COFFEE10";
private decimal PricePerCup => size switch
{
CupSize.Small => 2.80m,
CupSize.Medium => 3.20m,
_ => 3.60m,
} + (oatMilk ? 0.40m : 0m);
private decimal Total => Math.Round(cups * PricePerCup * (VoucherApplied ? 0.9m : 1m), 2);
// Runs after @bind has stored the new size. It may be async.
private async Task CheckStockAsync()
{
stockMessage = $"Checking {size} cups…";
await Task.Delay(600);
stockMessage = $"{size} cups are in stock. {PricePerCup.ToString("0.00", CultureInfo.InvariantCulture)} each.";
}
// Called with the raw text on every keystroke. Keep letters and digits, upper-case, at most 8.
private void SetVoucher(string? value)
{
var kept = new string((value ?? "").Where(char.IsLetterOrDigit).ToArray()).ToUpperInvariant();
voucher = kept.Length > 8 ? kept[..8] : kept;
}
public enum CupSize { Small, Medium, Large }
}
wwwroot/index.html
Download file ↗<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Coffee order</title>
<base href="/" />
<link rel="stylesheet" href="css/app.css" />
<link rel="stylesheet" href="TwoWayBinding.styles.css" />
</head>
<body>
<div id="app">
<p class="loading">Starting .NET…</p>
</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="." class="reload">Reload</a>
<span class="dismiss">✕</span>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
wwwroot/css/app.css
Download file ↗:root {
color-scheme: light dark;
--accent: #6b4eff;
--line: #d8d6e4;
--muted: #777;
}
body {
margin: 0;
font-family: -apple-system, system-ui, sans-serif;
line-height: 1.5;
}
#app {
max-width: 720px;
margin: 0 auto;
padding: 20px 16px 40px;
box-sizing: border-box;
}
a, button, input, label {
touch-action: manipulation;
}
h1 {
font-size: 1.8rem;
margin: 0 0 12px;
}
h1:focus {
outline: none;
}
h2 {
font-size: 1.15rem;
margin: 0 0 8px;
}
.loading {
padding: 32px 16px;
color: var(--muted);
}
.row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 12px 0;
}
input:not([type=checkbox]), select {
font: inherit;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
min-width: 0;
background: transparent;
color: inherit;
}
button {
font: inherit;
padding: 8px 14px;
border-radius: 8px;
border: 1px solid var(--line);
background: transparent;
color: inherit;
}
button.primary {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
button:disabled {
opacity: 0.45;
}
button.link {
border: none;
color: var(--accent);
padding: 4px 6px;
}
.muted {
color: var(--muted);
}
.card {
border: 1px solid var(--line);
border-radius: 12px;
padding: 14px 16px;
margin: 16px 0;
}
.card > :last-child {
margin-bottom: 0;
}
code {
font-family: ui-monospace, Menlo, monospace;
font-size: 0.9em;
overflow-wrap: anywhere;
}
label {
display: block;
margin: 10px 0;
}
label input:not([type=checkbox]),
label select {
display: block;
width: 100%;
margin-top: 4px;
box-sizing: border-box;
}
label.check {
display: flex;
align-items: center;
gap: 8px;
}
label.check input {
width: 20px;
height: 20px;
}
.card p {
margin: 6px 0;
}
.summary {
border-color: var(--accent);
}
#blazor-error-ui {
display: none;
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 12px 16px;
background: #ffe8a3;
color: #222;
}
Expected result
The note and its character count update on every key; the name updates only when you leave the box. Choosing Large shows "Checking Large cups…" and then "Large cups are in stock. 3.60 each." Both cups boxes always show the same number. "two" or "2.5" in the text box is replaced by the previous number, while clearing either box sets cups to 0. 31.02.2026 is replaced by the previous date, and a valid date such as 24.12.2026 also moves the date picker. The voucher box shows COFFEE10 as you type and the total drops by 10%. The order card reports "Current culture: invariant" in SharpRune's Preview; on a computer it usually shows the browser's language, such as en-US.
The project runs in the SharpRune app and with the .NET 9 SDK. Open C# practice runs the separate portable exercise.
C# companion practice
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
// A simplified copy of what @bind does with the text the browser sends:
// parse it and store it; store default(T) for an empty box; otherwise keep the old value.
var invariant = CultureInfo.InvariantCulture;
int cups = 2;
foreach (var text in new[] { "3", "two", "2.5", "12", "" })
{
string result;
if (int.TryParse(text, NumberStyles.Number, invariant, out int parsed))
{
cups = parsed;
result = "stored";
}
else if (text == "")
{
cups = default;
result = "empty, stored default";
}
else
{
result = "reverted";
}
Console.WriteLine($"int \"{text}\" -> {result}, cups = {cups}");
}
// int? accepts an empty box as null.
int? sugar = 1;
foreach (var text in new[] { "", "2" })
{
if (text == "") sugar = null;
else if (int.TryParse(text, NumberStyles.Number, invariant, out int parsed)) sugar = parsed;
Console.WriteLine($"int? \"{text}\" -> sugar = {(sugar is null ? "null" : sugar.Value.ToString(invariant))}");
}
// @bind:format="dd.MM.yyyy": the text must match the pattern exactly.
var pickup = new DateOnly(2026, 11, 20);
foreach (var text in new[] { "21.11.2026", "31.02.2026", "1.12.2026" })
{
bool ok = DateOnly.TryParseExact(text, "dd.MM.yyyy", invariant, DateTimeStyles.None, out var parsed);
if (ok) pickup = parsed;
Console.WriteLine($"date \"{text}\" -> {(ok ? "stored" : "reverted")}, box shows {pickup.ToString("dd.MM.yyyy", invariant)}, date picker gets {pickup.ToString("yyyy-MM-dd", invariant)}");
}
// @bind:set: the setter decides what is stored, and the box then shows that value.
foreach (var typed in new[] { "c", "coffee 1", "coffee10", "coffee10xyz" })
{
Console.WriteLine($"voucher \"{typed}\" -> {CleanVoucher(typed)}");
}
Console.WriteLine($"total for 3 Medium with oat milk and COFFEE10: {Total(3, "Medium", true, "COFFEE10").ToString("0.00", invariant)}");
Console.WriteLine($"total for 2 Large, no extras: {Total(2, "Large", false, "").ToString("0.00", invariant)}");
static string CleanVoucher(string value)
{
var kept = new string(value.Where(char.IsLetterOrDigit).ToArray()).ToUpperInvariant();
return kept.Length > 8 ? kept[..8] : kept;
}
static decimal Total(int cups, string size, bool oatMilk, string voucher)
{
decimal price = size switch { "Small" => 2.80m, "Medium" => 3.20m, _ => 3.60m } + (oatMilk ? 0.40m : 0m);
return Math.Round(cups * price * (voucher == "COFFEE10" ? 0.9m : 1m), 2);
}
C# practice output
int "3" -> stored, cups = 3 int "two" -> reverted, cups = 3 int "2.5" -> reverted, cups = 3 int "12" -> stored, cups = 12 int "" -> empty, stored default, cups = 0 int? "" -> sugar = null int? "2" -> sugar = 2 date "21.11.2026" -> stored, box shows 21.11.2026, date picker gets 2026-11-21 date "31.02.2026" -> reverted, box shows 21.11.2026, date picker gets 2026-11-21 date "1.12.2026" -> reverted, box shows 21.11.2026, date picker gets 2026-11-21 voucher "c" -> C voucher "coffee 1" -> COFFEE1 voucher "coffee10" -> COFFEE10 voucher "coffee10xyz" -> COFFEE10 total for 3 Medium with oat milk and COFFEE10: 9.72 total for 2 Large, no extras: 7.20
@bind keeps the last good value when text does not parse, but an empty box stores the default value of the type. Bind to int? or DateOnly? when "not entered" must differ from 0.