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.

public class UserController : ControllerBase {
    [BindProperty]
    public User? User { get; set; }
}
  • [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.

[BindProperties]
public class UserModel : PageModel {
    public User? User { get; set; }
}

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:

  1. Form fields

  2. The request body

  3. Route data

  4. Query string parameters

  5. Uploaded files (bound only to target types that implement IFormFile or IEnumerable<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.

builder.Services.AddControllers(options =>
{
    // puts the custom value provider after all built-in value providers
    options.ValueProviderFactories.Add(new CookieValueProviderFactory());
    // to make it the first in the list, call Insert() instead of Add()
    options.ValueProviderFactories.Insert(0, new CookieValueProviderFactory());
});

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