mercredi 31 mai 2023

DynamicForm Component that takes Generic Model Class as Parameter to Generate EditForm

I have a component called DynamicForm which accepts couple of Parameters including Generic Model Class.

@typeparam TModel

<EditForm Model="@Model" OnValidSubmit="@HandleFormSubmit">
    @foreach (var property in typeof(TModel).GetProperties())
    {
        @if (property.PropertyType == typeof(string))
        {
            <input class="form-control" id="@property.Name" @bind="@property.GetValue(Model)" />
        }
        else if (property.PropertyType == typeof(DateTime))
        {
            <input type="date" class="form-control" id="@property.Name" @bind="@property.GetValue(Model)" />
        }
    }

    <button type="submit" class="btn btn-primary">Submit</button>
</EditForm>

@code {
    [Parameter]
    public TModel Model { get; set; }

    [Parameter]
    public EventCallback<TModel> OnValidSubmit { get; set; }

    private Task HandleFormSubmit()
    {
        return OnValidSubmit.InvokeAsync(Model);
    }
}

what I am trying to achive is to generate Dynamic EditForm (Controls) based on Provided Model Class using following code

<DynamicForm TModel="FormModel" Model="@person" OnValidSubmit="HandleFormSubmit" />

@code {
    private FormModel person = new FormModel();

    private void HandleFormSubmit(FormModel model)
    {
        //Todo
    }
}

But I am getting following compile time errors on @bind="@property.GetValue(Model)"

  • Error (active) CS0131 The left-hand side of an assignment must be a variable, property or indexer
  • Error (active) CS1503 Argument 1: cannot convert from 'object' to 'System.DateTime'




Aucun commentaire:

Enregistrer un commentaire