我在 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()[email protected]">@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;
}
所以我得到這個錯誤
'提供的運算式包含不受支持的 InstanceMethodCallExpression1。'
這是因為
@(()=> @prop.GetValue(DataContext))
有沒有其他方法可以“正確”做到這一點?或通過建設者?謝謝并恭祝安康 !
uj5u.com熱心網友回復:
我認為有一個錯字:
@(()=> @prop.GetValue(DataContext))應該是@(()=> prop.GetValue(DataContext))
(這里第二個@符號不好)
請問可以試試嗎?
uj5u.com熱心網友回復:
ValidationMessage期望它可以分解以獲取屬性名稱的運算式。它使用Model它從級聯EditContext和屬性中獲取的For來查詢ValidationMessageStore針對EditContext模型/屬性記錄的任何訊息。
您收到錯誤是因為For格式不正確。
這就是構建動態表單的問題:您還需要構建與之配套的基礎設施。
這是 Blazor 存盤庫中的相關代碼 - https://github.com/dotnet/aspnetcore/blob/66104a801c5692bb2da63915ad877d641c45cd42/src/Components/Forms/src/FieldIdentifier.cs#L91 (祝你好運!)
uj5u.com熱心網友回復:
好的,我終于在某個地方找到了類似的東西并進行了一些修改,它適用于未來的搜索者:
@if (ShowValidationUnderField)
{
@FieldValidationTemplate(@prop.Name)
}
在代碼中:
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();
};
問候
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/462062.html
上一篇:用于時間跟蹤的正則運算式驗證
