Skip to content

Commit

Permalink
Adds support of other Nullable types binding
Browse files Browse the repository at this point in the history
  • Loading branch information
anton-zhukov committed Jul 20, 2019
1 parent b8ec062 commit 500e7c5
Showing 1 changed file with 18 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,27 +26,37 @@ public object BuildModel(PropertyInfo propertyInfo, object value)
var underlyingType = Nullable.GetUnderlyingType(propertyType);

// Property is GUID.
if ((propertyType == typeof(Guid) || underlyingType == typeof(Guid)) && Guid.TryParse(value.ToString(), out var guid))
if (propertyType == typeof(Guid) && Guid.TryParse(value.ToString(), out var guid))
return guid;
if (underlyingType == typeof(Guid))
{
if (Guid.TryParse(value.ToString(), out guid))
return guid;
return null;
}

// Property is Enum.
if (propertyType.IsEnum)
return convertToEnum(propertyType, value.ToString());
if (underlyingType != null && underlyingType.IsEnum)
{
if (string.IsNullOrWhiteSpace(value.ToString()))
return null;
return convertToEnum(underlyingType, value.ToString());
}

// Other Nullable types
if (underlyingType != null)
{
if (string.IsNullOrEmpty(value.ToString())) return null;
propertyType = underlyingType;
}

return Convert.ChangeType(value, propertyType);
}

object convertToEnum(Type type, string val)
{
// if (type.GetEnumNames().Contains(val, StringComparer.InvariantCultureIgnoreCase))
// return Enum.Parse(type, val, true);
//
// if (!int.TryParse(val, out var num)) return null;

// return Enum.ToObject(type, num);

if (int.TryParse(val, out var num))
return Enum.ToObject(type, num);

Expand Down

0 comments on commit 500e7c5

Please sign in to comment.