问题
I'm playing with Blazor and I'd like to create a dynamically generated form, which is part of a grid.
The entity type of the data is passed to the grid and this is the base of the form. The problem I'm facing now is @bind-Value
, which is needed to be able to edit the given entity.
I use BlazorStrap, and it is a Blazor Server Side project.
I have the following code in the razor file:
@{
string bind = $"{nameof(_editedItem)}.{propertyInfo.Name}";
}
<BSBasicInput InputType="InputType.Text"
id="@propertyInfo.Name"
@bind-Value="@bind"/>
The problematic part is the last line. Always the _variableName.PropertyName
is displayed instead of pulling out the value from the object.
The proper code should look like this:
<BSBasicInput InputType="InputType.Text"
id="@propertyInfo.Name"
@bind-Value="_variableName.PropertyName"/>
What I tried so far:
- multiple flavors of the syntax, but, since I'm not really experienced with Razor syntax, after I while I hit a wall
- debugging shows that the vairable I'd like to edit gets its values, so the problem somewhere the generated
@bind-Value
value - I also checked the generated code (the .g files), but I haven't found any smelly there (please, find it below)
- I haven't created yet a POC without dynamically generated forms, because it would take a few hours to create somthing similar complexity.
What is the solution here?
#nullable restore
#line 24 "/../..ModalEdit.razor"
bind
#line default
#line hidden
#nullable disable
, 31, Microsoft.AspNetCore.Components.EventCallback.Factory.Create(this, Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.CreateInferredEventCallback(this,
__value => bind = __value, bind)));
__builder4.AddMarkupContent(32, "\n");
回答1:
you cant bind, but you can use callbacks and lambda functions to archive the same results:
@if (user != null)
{
@foreach (var property in user.GetType().GetProperties())
{
<Field>
<FieldLabel>@(property.Name): @(property.PropertyType.FullName)</FieldLabel>
@switch (property.PropertyType.FullName)@*Chose editing style*@
{
case "System.String":
<TextEdit Text="@property.GetValue(user)?.ToString()" TextChanged="value => property.SetValue(user, value)" />
break;
case "System.Boolean":
<Switch TValue="bool" Checked="(bool)property.GetValue(user)" CheckedChanged="value => property.SetValue(user, value)" />
break;
default: /*Unsuported/Not implemented editing*/
<TextEdit Text="@property.GetValue(user)?.ToString()" Disabled="true" />
break;
}
</Field>
}
}
I'm using Blazorise controls in this example, but you can use any.
来源:https://stackoverflow.com/questions/59570685/how-to-generate-dynamically-blazors-bind-value