Model Binding
Controllers and Razor pages work with data that comes from HTTP requests.
For example, route data may provide a record key, and posted form fields may provide values for the properties of the model. Model binding automates the process retrieve each of these values and convert them from strings to .NET types.
The model binding system:
Retrieves data from various sources such as route data, form fields, and query strings.
Provides the data to controllers and Razor pages in method parameters and public properties.
Converts string data to .NET types and updates properties of complex types.
Attribute Binding
[BindProperty]
attribute
this attribute can be applied to a public property of a ControllerBase
or PageModel
class to cause model binding to target that property.
[BindProperties]
attribute
this attribute can be applied to a ControllerBase
or PageModel
class to cause model binding to target all the public properties of the class.
By default, properties are not bound to data for HTTP GET requests. To do so, we just need to set the SupportsGet
property to true
. For Example:
[BindProperty(SupportsGet = true)]
for method[BindProperties(SupportsGet = true)]
for class
Binding Sources
By default, model binding gets data in the form of key-value pairs from the following order of sources in an HTTP request:
Form fields
The request body
Route data
Query string parameters
Uploaded files (bound only to target types that implement
IFormFile
orIEnumerable<IFormFile>
)
If we do not want to use the default source of model binding, we can use the following attributes to specify the source:
Custom Model Binding Sources
Source data is provided to the model binding system by value providers. You can write and register custom value providers that get data for model binding from other sources. For example, you might want data from cookies or session state.
To get data from a new source:
Create a class that implements
IValueProvider
.Create a class that implements
IValueProviderFactory
.Register the custom value provider factory classes in
Program.cs
.
The record of what data is bound to the model, and any binding or validation errors, is stored in ControllerBase.ModelState
or PageModel.ModelState
.
Last updated