dotnet / dotnet/aspnetcore

Model binding with non-default constructor

Open
#43,737 11 comments 1 reaction 0 assignees View on GitHub
area-mvc feature-model-binding
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

It is not possible to bind a model using a constructor unless using record types.

### Describe the solution you'd like

It would be good to allow model binding with non-default constructors on types that are not records. I don't have a full design to hand, but for a first draft:

* If a type has a constructor `Foo(int? bar, string baz)` then the parameters should be matched like properties are now (perhaps with some changes wrt. casing rules): the binder would look for keys `Bar` and `Baz` in the request.
* Complex types in the constructor would be matched similarly - A constructor `Quux(Foo f, int blah)` would use keys `F.Bar`, `F.Baz` and `Blah`.
* Writeable properties that exist but no where matching parameter is found in the constructor would be bound as they are currently
* Types with multiple constructors would be something to consider - perhaps an annotation like `[BindUsing]` on the one intended for binding?
* Perhaps there should be some annotation that marks a constructor parameter as handling a property that doesn't havea matching name? Something like `[Binds("propertyName")]`

### Additional context

Is this something that a PR would be accepted for? I can't guarantee I'd ever be able to do it, but never say never, hm?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.