I just found out that GetType().GetProperties() even exists, is it possible to use this way?
The goal is to use a loop to get all properties on a specific entity without having to hardcode every property inside the HTML, update every edited property and save the new info in an OnPost with the help of the [BindProperty] annotation. I'm unable to correctly bind with the asp-for taghelper.
<form method="post">
@foreach (var prop in Model.Product.GetType().GetProperties())
{
<label asp-for="@prop.Name"></label>
<input asp-for="@prop.GetValue(Model.Product)" class="form-control" />
}
<button type="submit" class="btn btn-primary">Update</button>
</form>
Running this code gives me the following exception:
InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
If I use value="@prop.GetValue(Model.Product)" inside the tag I correctly get the information when loading the edit page. But when submitting the form I don't get the new values previously entered.
Here's the model from the modelpage
[BindProperty]
public ProductModel? Product { get; set; }
OnGet()
{
Product = db.GetProduct(id);
}
Thanks for taking your time reading this!