panoptes/src/PanoptesFrontend/Pages/DynamicTable.razor

77 lines
2.5 KiB
Plaintext

@using System.Linq.Dynamic.Core
@inject IHttpService httpService
@using PanoptesFrontend.Services
<RadzenDataGrid @bind-Value=@selectedItems Data="@data" TItem="IDictionary<string, object>" ColumnWidth="200px"
AllowFiltering="true" FilterPopupRenderMode="PopupRenderMode.OnDemand" FilterMode="FilterMode.Advanced" AllowPaging="true" AllowSorting="true">
<Columns>
@foreach(var column in columns)
{
<RadzenDataGridColumn TItem="IDictionary<string, object>" Title="@column.Key" Type="column.Value"
Property="@GetColumnPropertyExpression(column.Key, column.Value)" >
<Template>
@context[@column.Key]
</Template>
</RadzenDataGridColumn>
}
</Columns>
</RadzenDataGrid>
<button @onclick="Update">Update Table</button>
@code {
IList<IDictionary<string, object>> selectedItems;
[Parameter]
public List<Dictionary<string, object>> data { get; set; }
[Parameter]
public int TableId {get; set;}
public IDictionary<string, Type> columns { get; set; }
public string GetColumnPropertyExpression(string name, Type type)
{
var expression = $@"it[""{name}""].ToString()";
if (type == typeof(int))
{
return $"int.Parse({expression})";
}
else if (type == typeof(DateTime))
{
return $"DateTime.Parse({expression})";
}
return expression;
}
protected override async Task OnInitializedAsync()
{
// Generate the columns dynamically based on the properties of the first object in the list
var firstItem = data.FirstOrDefault();
if (firstItem != null)
{
columns = firstItem.ToDictionary(p => p.Key, p => p.Value.GetType());
foreach (var column in columns.ToList())
{
if (column.Value != typeof(int) && column.Value != typeof(DateTime))
{
columns[column.Key] = typeof(string);
}
}
}
}
private async Task Update()
{
string module = "localhost:8080";
var response = await httpService.GetAsync<TableComponent>($"http://localhost:10000/{module}/{TableId}");
if (response.Data != null)
{
data.Clear();
data.AddRange(response.Data);
}
await InvokeAsync(() => StateHasChanged());
}
}