AspNetCore.Docs
AspNetCore.Docs copied to clipboard
Model Binding Request Data
ASP.NET MVC -> Models -> Model Binding Request Data
- What is Model Binding
- Binds request data to parameters of your actions
- Default sources of data
-
- Form data, 2. route values, 3.query parameters
- Support for jQuery provided values too
- Data handled as name-value pairs
-
- How named values get bound to action parameters
- Simple types: .NET simple types, anything with a string converter
- Bound using parameter name
- Handling of complex objects
- Binds to public settable properties
- Type must have a public default constructor
- Properties bound by trying:
- Parameter name as a prefix followed by a dot (ex. param_name.property_name)
- Falls back to just the property name
- Recurses for complex type properties
- Collections: parameter_name[index] or just [index]
- Any IEnumerable (as long as the property is settable)
ICollection<T>supported for read only properties- Array properties must be settable
- Dictionaries: parameter_name[key] or just [key]
- The key must be a simple type
- Assignments happen from bottom up
- Then validation happens
- Errors are described in the ModelStateDictionary (available via ModelState property on Controller)
- We general don't throw
- Simple types: .NET simple types, anything with a string converter
- Special data types
- IFormFile - form file upload
- IFormCollection - collection of the form data
- Cancelation token
- Attributes
[BindRequired]- Model state error if property/class not bound[BindNever]- Never bind to this property/class[FromHeader],[FromQuery],[FromRoute],[FromForm]- Control the name with the Name property
- Generally supported on parameters, properties and classes
[FromServices]- only supported on action parameters[FromBody] (see formatting)[ModelBinder]- Override the model binder, binding source and name
- Binding formatted data from the request body
- Use
[FromBody]to indicate what should be bound using input formatters - Input formatter selected based on the Content-Type header and the type of the parameter
- Default input formatters: JSON
- Based off of JSON.NET
- Optionally add XML input formatter by referencing Microsoft.AspNet.Mvc.Formatters.Xml and adding the input formatters you want.
AddXmlDataContractSerializerFormatters(), orAddXmlSerializerFormatters()
- Configure specific input formatters via options (modify the instance in
MvcOptions.InputFormatters)
- Use
Link to model validation
Move extensibility into a separate topic:
- Custom model binders and sources
- Custom value provider
can i have early access for the docs?
See https://github.com/aspnet/Docs/pull/933.
@danroth27
Closed https://github.com/aspnet/Docs/pull/933 4203eada2a8b5f4455011e35e305e4e7afb4afef