Skip to content

Commit bef0ac9

Browse files
Add a note about model binding record types (#19968)
* Add a note about model binding record types * Update model-binding.md * Update model-binding.md * Update model-binding.md Co-authored-by: Rick Anderson <3605364+Rick-Anderson@users.noreply.github.com>
1 parent 09c391c commit bef0ac9

1 file changed

Lines changed: 34 additions & 1 deletion

File tree

aspnetcore/mvc/models/model-binding.md

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,8 +379,41 @@ For `Dictionary` targets, model binding looks for matches to *parameter_name* or
379379
* selectedCourses["1050"]="Chemistry"
380380
* selectedCourses["2000"]="Economics"
381381

382-
<a name="glob"></a>
382+
::: moniker range="> aspnetcore-5.0"
383+
384+
## Constructor binding and record types
385+
386+
Model binding requires that complex types have a parameterless constructor. Both `System.Text.Json` and `Newtonsoft.Json` based input formatters support deserialization of classes that do not have a parameterless constructor.
387+
388+
C# 9 introduces record types which are a great way to succintly represent data over the network. ASP.NET Core adds support for model binding and validating record types with a single constructor.
389+
390+
```C#
391+
public record Person([Required] string Name, [Range(0, 150)] int Age);
392+
393+
public class PersonController
394+
{
395+
public IActionResult Index() => View();
396+
397+
[HttpPost]
398+
public IActionResult Index(Person person)
399+
{
400+
// ...
401+
}
402+
}
403+
404+
// Person/Index.cshtml
405+
@model Person
406+
407+
Name: <input asp-for="Name" />
408+
...
409+
Age: <input asp-for="Age" />
410+
```
383411

412+
When validating record types, the runtime looks for validation metadata specifically on parameters rather than on properties.
413+
414+
::: moniker-end
415+
416+
<a name="glob"></a>
384417
## Globalization behavior of model binding route data and query strings
385418

386419
The ASP.NET Core route value provider and query string value provider:

0 commit comments

Comments
 (0)