I have an ASP.NET Core 1.1 API that takes in a DTO parameter called DetParameterCreateDto
. The problem I am having is that one of the property names is dynamic (instrument_complete
). The name is actually [instrument]_complete
where [instrument]
is the name of the instrument.
So if the instrument
is my_first_instrument then the property name will really be my_first_instrument_complete
.
After posting on here and searching the web, it seems like the best solution is to create a custom model binder. I am wondering if there is a way to just custom map the instrument_complete
parameter, and set the rest to the default map. I feel like my solution below is not the best solution because of performance of having to map and convert all the parameters, and because creating a new model will not transfer the model state; so will clear any validation errors. I may be wrong but this is what I believe
DTO
public class DetParameterCreateDto
{
public int Project_Id { get; set; }
public string Username { get; set; }
public string Instrument { get; set; }
public short Instrument_Complete { get; set; }
// Other properties here...
}
Custom Model Binder
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var instrumentValue = bindingContext.ValueProvider.GetValue("instrument").FirstValue;
var model = new DetParameterCreateDto()
{
Project_Id = Convert.ToInt32(bindingContext.ValueProvider.GetValue("project_id").FirstValue),
Username = bindingContext.ValueProvider.GetValue("username").FirstValue,
Instrument = instrumentValue,
Instrument_Complete = Convert.ToInt16(bindingContext.ValueProvider
.GetValue($"{instrumentValue}_complete").FirstValue),
};
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}