mardi 7 avril 2020

Blazor : is it possible to bind a generic item to a property by its name using reflection?

I'm trying to get a generic editor template using Blazor that binds to properties found by reflection as follows :

@typeparam TItem

@foreach (var propertyName in FieldsList) {
    <div>
        <InputText id="name" @bind-Value="@getBindProperty(propertyName)" />
    </div>
}

@functions {
    [Parameter]
    public TItem ItemEditModel { get; set; }

    public string[] FieldsList {
        get {
            // get all properties decorated with some custom attribute...
            return typeof(TItem).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(MyCustomAttribute))).Select(x => x.Name).ToArray();
        }
    }

    public string getBindProperty(string propName) {
        return string.Format("{0}.{1}", nameof(ItemEditModel), propName);
    }
}

The above is not accepted as The left-hand side of an assignment must be a variable, property or indexer.

So I cannot bind to a property by its name, so I went on trying other syntax like

<InputText id="name" @bind-Value="ItemEditModel.propertyName" />

This is not accepted either as TItem does not contain a definition of 'propertyName'.

Well all the above make sense - but the key question - is there anything to be done about it, or is it impossible to bind a control to a property by its name?

BONUS QUESTION: If it is actually possible to do this, is there a way to make a switch depending on the property type (typically, only atomic types like ´string´, ´DateTine´, ´int´, ´double´, ´bool´...)?





Aucun commentaire:

Enregistrer un commentaire