| | 1 | | using Microsoft.AspNetCore.Mvc.ModelBinding; |
| | 2 | | using System; |
| | 3 | | using System.Collections.Generic; |
| | 4 | | using System.Threading.Tasks; |
| | 5 | |
|
| | 6 | | namespace Plainquire.Filter.Mvc.ModelBinders; |
| | 7 | |
|
| | 8 | | /// <summary> |
| | 9 | | /// ModelBinder for <see cref="EntityFilter{TEntity}"/> |
| | 10 | | /// Implements <see cref="IModelBinder" /> |
| | 11 | | /// </summary> |
| | 12 | | /// <seealso cref="IModelBinder" /> |
| | 13 | | public class EntityFilterSetModelBinder : IModelBinder |
| | 14 | | { |
| | 15 | | private readonly IDictionary<Type, (ModelMetadata, IModelBinder)> _entityFilterBinders; |
| | 16 | |
|
| | 17 | | /// <summary> |
| | 18 | | /// Initializes a new instance of the <see cref="EntityFilterSetModelBinder"/> class. |
| | 19 | | /// </summary> |
| | 20 | | /// <param name="entityFilterBinders">The entity filter binders.</param> |
| | 21 | | /// <autogeneratedoc /> |
| | 22 | | public EntityFilterSetModelBinder(IDictionary<Type, (ModelMetadata, IModelBinder)> entityFilterBinders) |
| 2 | 23 | | => this._entityFilterBinders = entityFilterBinders; |
| | 24 | |
|
| | 25 | | /// <inheritdoc /> |
| | 26 | | public async Task BindModelAsync(ModelBindingContext bindingContext) |
| | 27 | | { |
| | 28 | | if (bindingContext == null) |
| | 29 | | throw new ArgumentNullException(nameof(bindingContext)); |
| | 30 | |
|
| | 31 | | var entityFilterSet = Activator.CreateInstance(bindingContext.ModelType) |
| | 32 | | ?? throw new InvalidOperationException($"Cannot create instance of filter set '{bindingContext.ModelType.Nam |
| | 33 | |
|
| | 34 | | var entityFilterProperties = entityFilterSet.GetType().GetProperties(); |
| | 35 | | foreach (var entityFilter in entityFilterProperties) |
| | 36 | | { |
| | 37 | | var (modelMetadata, modelBinder) = _entityFilterBinders[entityFilter.PropertyType]; |
| | 38 | |
|
| | 39 | | var filterBindingContext = DefaultModelBindingContext.CreateBindingContext( |
| | 40 | | bindingContext.ActionContext, |
| | 41 | | bindingContext.ValueProvider, |
| | 42 | | modelMetadata, |
| | 43 | | bindingInfo: null, |
| | 44 | | bindingContext.OriginalModelName); |
| | 45 | |
|
| | 46 | | await modelBinder.BindModelAsync(filterBindingContext); |
| | 47 | |
|
| | 48 | | entityFilter.SetValue(entityFilterSet, filterBindingContext.Result.Model); |
| | 49 | | } |
| | 50 | |
|
| | 51 | | bindingContext.Result = ModelBindingResult.Success(entityFilterSet); |
| | 52 | | } |
| | 53 | | } |