动态组件提供的表达式的 blazor validationMessage 包含不支持的 InstanceMethodCallExpression1

Dor*_*ian 1 c# validation blazor

我在 blazor 中构建一些动态表单生成器,我对这部分有疑问

 @using Microsoft.AspNetCore.Components.CompilerServices
 @using System.Text.Json
 @using System.ComponentModel.DataAnnotations
 @typeparam Type


<EditForm Model="@DataContext" OnValidSubmit="OnValidSubmit">
<DataAnnotationsValidator/>
 @foreach (var prop in  typeof(Type).GetProperties())
{
    <div class="mb-3">
     <label for= "@this.idform.ToString()_@prop.Name">@Label(@prop.Name) : </label> 
     
        @CreateStringComponent(@prop.Name)

        @if (ShowValidationUnderField)
        {
                   <ValidationMessage For = "@(()=> @prop.GetValue(DataContext))"></ValidationMessage>

        }
      </div>
      
    
}

@code {
[Parameter] public Type? DataContext { get; set; } 

[Parameter] 
public EventCallback<Type> OnValidSubmitCallback { get; set; }

[Parameter]
public bool ShowValidationSummary { get; set; } = false;

[Parameter]
public bool ShowValidationUnderField { get; set; } = true;
}
Run Code Online (Sandbox Code Playgroud)

所以我收到这个错误

“提供的表达式包含不支持的 InstanceMethodCallExpression1。”

这是因为

@(()=> @prop.GetValue(DataContext))
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以“正确”地做到这一点吗?或通过建设者?感谢致敬 !

Dor*_*ian 5

好吧,我终于在某个地方找到了类似的东西并进行了一些修改,它对未来的搜索者来说是有效的:

@if (ShowValidationUnderField)
{
     @FieldValidationTemplate(@prop.Name)
}
Run Code Online (Sandbox Code Playgroud)

并在代码中:

 public RenderFragment? FieldValidationTemplate(string fld) => builder =>
   {

       PropertyInfo? propInfoValue = typeof(ContextType).GetProperty(fld);

       var access = Expression.Property(Expression.Constant(DataContext, typeof(ContextType)), propInfoValue!);
       var lambda = Expression.Lambda(typeof(Func<>).MakeGenericType(propInfoValue!.PropertyType), access);

       builder.OpenComponent(0, typeof(ValidationMessage<>).MakeGenericType(propInfoValue!.PropertyType));
       builder.AddAttribute(1, "For", lambda);
       builder.CloseComponent();


   };
Run Code Online (Sandbox Code Playgroud)

问候