I have created a modelbinder using reflection to set property values from a csv file. I am using Convert.ChangeType
which has worked for most cases but now a date value needs to be parsed to my DateTime
property. The format in the csv is YYYYMMDD. The code I have so far:
foreach (var property in matchedModel)
{
Type propType = Nullable.GetUnderlyingType(property.Value.PropertyType) ??
property.Value.PropertyType;
var value = string.IsNullOrEmpty(data.Value[property.Key]) ? null :
Convert.ChangeType(data.Value[property.Key], propType);
property.Value.SetValue(instance, value, null);
}
The property
variable is the relevant property that needs to be set. Since I had some nullable properties I had to use the Nullable.GetUnderlyingType
.
The problem is with the value
not being converted to a proper DateTime
as explained above. The easy solution would be to have something like:
if(property is datetime) do value conversion
However this would be too hardcoded and I want something more generic/dynamic. What would be the best way to approach this?
Aucun commentaire:
Enregistrer un commentaire