如何动态生成blazor的@bind-Value?

Say*_*ndo 6 c# razor blazor-server-side

我正在使用 Blazor,我想创建一个动态生成的表单,它是网格的一部分。数据的实体类型被传递到网格,这是表单的基础。我现在面临的问题是@bind-Value,需要能够编辑给定的实体。

我使用BlazorStrap,它是一个 Blazor 服务器端项目。

我的剃刀文件中有以下代码:

@{
string bind = $"{nameof(_editedItem)}.{propertyInfo.Name}";
}
<BSBasicInput InputType="InputType.Text"
              id="@propertyInfo.Name"
              @bind-Value="@bind"/>
Run Code Online (Sandbox Code Playgroud)

有问题的部分是最后一行。始终_variableName.PropertyName显示而不是从对象中提取值。

正确的代码应该如下所示:

<BSBasicInput InputType="InputType.Text"
              id="@propertyInfo.Name"
              @bind-Value="_variableName.PropertyName"/>
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试过的:

  • 语法的多种风格,但是,由于我对 Razor 语法并没有真正的经验,在我碰壁之后
  • 调试显示我想要编辑的变量获取了它的值,所以问题出在生成的@bind-Value值上
  • 我还检查了生成的代码(.g 文件),但我没有发现任何异味(请在下面找到它)
  • 我还没有创建没有动态生成表单的 POC,因为创建类似复杂的东西需要几个小时。

这里的解决方案是什么?

#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");
Run Code Online (Sandbox Code Playgroud)

小智 5

您无法绑定,但可以使用回调和 lambda 函数来存档相同的结果:

            @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>
                }
            }
Run Code Online (Sandbox Code Playgroud)

我在本示例中使用 Blazorise 控件,但您可以使用任何控件。