Make CollectionModelBinder
better extensible for custom model binders
#60605
Labels
api-suggestion
Early API idea and discussion, it is NOT ready for implementation
area-mvc
Includes: MVC, Actions and Controllers, Localization, CORS, most templates
Background and Motivation
I came across the need to bind a collection with non-sequential indices in my project. While researching I found that I am not alone with this, and that this behavior seems to bother people at least since 2008.
Our use case is, to have a list of objects in a form. Via HTMX new lines can be appended to the end, and rows in the middle can be removed. Thus we can guarantee, that indices are unique, but might have gaps between them.
I looked at the
CollectionModelBinder
and found, that our desired behavior could be achieved by changing thebreak
here to acontinue
.However, since the
BindComplexCollectionFromIndexes
method is internal, I can not derive a custom model binder and overwrite just this one part.Furthermore, to reuse as much as possible from the
CollectionModelBinderProvider
, I suggest adding an optional model binder type parameter to the constructor.I do not propose adding the
NonSequentialIndexCollectionModelBinder
to ASP.NET core. I am fine if this lives in our project code. However, with these few changes, we could reuse most of the standard code.Proposed API
I suggest simple changes in three classes. First, the
CollectionModelBinder
should allowBindComplexCollectionFromIndexes
to be overridden and make the needed_maxModelBindingCollectionSize
available to derived classes:Second, the
CollectionModelBinderProvider
should gain a type parameter, to be able to provide custom collection model binders:Third, the
ExplicitIndexCollectionValidationStrategy
should become public, so that it can be used in custom model binders:Usage Examples
Then we can derive a simple deviating model binder, that allows gaps and non-zero based indices:
Alternative Designs
The most suggested workaround seems to be to add hidden fields for the Index, but this feels clunky.
Risks
As this change only allows to reuse ASP.NET code as much as possible in a custom model binder and not change any behavior or usage, I see no risks.
The text was updated successfully, but these errors were encountered: