Binding to an Object with Reflection

Viewed 30

Is it possible to bind to an Object of type Object in Blazor?

The reason I don't know the Type is because I use the same Model Class for different Object types and the Model determines the Object Type with reflection.

Currently what I am doing, is as follow:

@foreach (EntityProperty property in model.EntityProperties)
{
    <input type="text" value="@GetValue(property.PropertyName)" @oninput="@((e) => SetValue(property.PropertyName, e.Value))" />
}

Where GetValue() is as follow:

private object GetValue(string PropertyName)
{
    return model.EntityObject.GetType().GetProperty(PropertyName).GetValue(model.EntityObject);
}

And SetValue() is:

private void SetValue(string PropertyName, object Value)
{
    PropertyInfo propertyInfo = model.EntityObject.GetType().GetProperty(PropertyName);
    propertyInfo.SetValue(model.EntityObject, Convert.ChangeType(Value, propertyInfo.PropertyType), null);
}

This works 100%, I was just wondering if binding directly to the Object Variable's Property would be possible, as it would simplify the code in my Model.

0 Answers
Related