Binder model for custom property type

In an ASP.NET Core project, I do the following:

public async Task<IActionResult> Get(ProductModel model) { } public class ProductModel { public Filter<Double> Price { get; set; } } 

I have a base filter class and RangeFilter as follows:

 public class Filter<T> { } public class RangeFilter<T> : Filter<T> { public abstract Boolean TryParse(String value, out Filter<T> filter); } 

I am passing the string ( "[3.34;18.75]" ) to the action as a price.

I need to create a ModelBinder where I use the TryParse method to try to convert this String to RangeFilter<Double> to define the ProductModel.Price property.

If TryParse fails, for example, returns false , the ProductModel.Price property becomes null.

How can I do that?

+8
c # asp.net-core
source share
1 answer

If you want to move the parsing method to a static class, this will become a little more doable.

Parser

 public static class RangeFilterParse { public static Filter<T> Parse<T>(string value) { // parse the stuff! return new RangeFilter<T>(); } } public abstract class Filter<T> { } public class RangeFilter<T> : Filter<T> { } 

Model

 public class ProductModel { [ModelBinder(BinderType = typeof(RangeModelBinder))] public Filter<double> Price { get; set; } } 

Binder

 public class RangeModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { try { var input = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString(); var inputType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; // invoke generic method with proper type var method = typeof(RangeFilterParse).GetMethod(nameof(RangeFilterParse.Parse), BindingFlags.Static); var generic = method.MakeGenericMethod(inputType); var result = generic.Invoke(this, new object[] { input }); bindingContext.Result = ModelBindingResult.Success(result); return Task.CompletedTask; } catch(Exception) // or catch a more specific error related to parsing { bindingContext.Result = ModelBindingResult.Success(null); return Task.CompletedTask; } } } 
+5
source share

All Articles