📒
Notes
Cloud ComputingData Science/AIGame Development
  • Home
  • Big O
  • Data Structures & Algorithms
    • Data Structures
      • Array
      • Stack
      • Queue
      • Linked List
      • Binary Tree
    • Algorithms
      • Searching
      • Sorting
      • Graphs
        • Searching
        • Minimum Spanning Tree
        • Shortest Path Algorithms
      • String Algorithms
  • Object Oriented Programming
  • Languages
    • HTML/CSS
      • CSS
    • C++
    • C#
      • Types
      • Keywords
        • Modifiers
          • Access Modifiers
        • Method Parameters
      • Operators and Expressions
      • Collections
      • Constructors
      • Delegates
      • Indexers
      • Concepts
      • Features
        • LINQ
          • Operators
          • Working with Data
          • Methods
          • Resources
        • Asynchronous Programming
        • Reflection
    • Dart
    • GraphQL
    • JavaScript
      • Variable and Parameter
      • Built-in objects
        • Array
        • Built-in Functions
      • Functions
      • Classes
      • Prototype
      • Libraries
        • jQuery
        • React
          • Components
          • State and Lifecycle
          • Hooks
            • useState
            • useEffect
          • Resources
      • Testing Framework
      • Web APIs
    • Kotlin
      • Basics
    • Python
      • Basics
      • Data Structures
      • Functions
      • Resources
        • Flask
    • SQL
      • Basics
      • Operators
      • JOINs
      • Aggregations
      • Subqueries
      • Views
      • Functions
        • Window Functions
      • Stored Procedures
      • Performance Tuning
      • Extras
    • Resources
  • 🌐Web Frameworks
    • Angular
      • Templates
      • Directives
        • Attribute Directives
        • Structural Directives
    • ASP.NET
      • Fundamentals
        • Dependency Injection
        • Middleware
        • Session & State Management
      • Web apps
        • MVC
          • Controllers
            • Filters
          • Models
            • Model Binding
            • Model Validation
          • Views
            • Tag Helpers
            • View Components
          • Features
        • Client-side development
      • Web APIs
        • Controller-based APIs
        • Minimal APIs
        • OpenAPI
        • Content Negotiation
      • SignalR
      • Host and Deploy
        • IIS
      • Security
    • Django
      • The Request/Response Cycle
    • Terminologies
      • Web Server
        • Internet Information Services
    • Resources
  • 📱App Frameworks
    • Introduction
      • Resources
    • Xamarin
      • Lifecycle
      • Custom Renderers & Effects
      • Behaviors
      • Triggers
      • Gestures
      • Commands
      • Dependency Service in XF
      • Libraries
      • Showcase
    • .NET MAUI
      • Controls
      • Navigation
      • Storage Options
  • Multi-Platform Frameworks
    • .NET
      • .NET Framework
        • ADO.NET
        • WCF
      • Fundamentals
        • Logging
        • Testing
      • Advanced
        • Asynchronous Programming
        • Parallel Programming
        • Threading
        • Memory Management
          • Garbage Collection
    • Flutter
  • Object-Relational Mappers
    • Entity Framework
      • Application Models
      • Configuration
      • Setting Up
      • Advanced
  • Databases
    • Introduction
      • DBMS Architecture
      • Normalization
      • Database Transaction Models
    • Relational Databases
      • Microsoft SQL Server
        • Basics
        • Functions
        • Stored Procedures
        • Error Handling
        • Log Shipping
        • Querying and Manipulating JSON data
        • Statements
        • Topics
        • Extras
    • Non-Relational Databases
      • MongoDB
      • Redis
        • Data Structures
        • Introduction
        • Managing Database
  • Tools
    • Version Control
      • Git
        • Setup and Config
        • Basics
          • Sharing and Updating Projects
        • Resources
      • Perforce Helix
    • GitHub
    • Powershell
  • Software Development
    • Software Development Life Cycle
    • Software Design Patterns
      • GoF Design Patterns
      • Architectural Patterns
        • MVC
        • MVVM
        • N-tier Architecture
        • Onion Architecture
        • Data Transfer Objects
      • CQRS
    • Software Design Principles
      • S.O.L.I.D. Priniciple
  • System Design
    • Topics
      • Load Balancing
  • Topics
    • JWT
    • Caching
      • Static vs Dynamic Caching
    • OSI model
      • HTTP
    • Glossary
    • API
      • SOAP
      • REST
    • Microservices
    • WebHooks
    • Practice
    • Operating Systems
      • Windows
    • Architecture
  • 🔖Bookmarks
  • 🔗Resources
Powered by GitBook
On this page
  • Attribute Binding
  • Binding Sources
  • Custom Model Binding Sources

Was this helpful?

  1. Web Frameworks
  2. ASP.NET
  3. Web apps
  4. MVC
  5. Models

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:

[FromRoute]

Gets values from route data.

[FromQuery]

Gets values from the query string (?).

[FromHeader]

Gets values from HTTP headers.

[FromBody]

Gets values from the request body.

[FromForm]

Gets values from posted form fields.

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.

PreviousModelsNextModel Validation

Last updated 2 years ago

Was this helpful?

🌐