【发布时间】:2021-03-31 06:53:34
【问题描述】:
Docs 的这一部分描述了如何显示验证消息。
<ValidationMessage For="() => Parameters.PropertyA"></ValidationMessage>
如何动态设置ValidationMessage.For属性?
由于For 是Expression<Func<TValue>> 类型,我想传递一个Func,但这不能编译:
[Parameter]
public Func<string> PropertyLocator { get; set; }
<ValidationMessage For="PropertyLocator"></ValidationMessage>
这会编译,但不会正确解析验证消息
<ValidationMessage For="() => PropertyLocator"></ValidationMessage>
我还尝试使 Component 具有通用性,以便它知道 Parameters 类型:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Components;
public partial class MyComponent<TParam>
{
[Parameter]
public TParam Parameters { get; set; }
[Parameter]
public Func<TReportParam, string> PropertyLocator { get; set; }
}
@using System.Linq.Expressions
@typeparam TParam
<ValidationMessage For="@((Expression<Func<string>>)(() => PropertyLocator(this.Parameters)))"></ValidationMessage>
<MyComponent TParam="MyParameters" Parameters="BindToSomeValue" PropertyLocator="(parameters) => parameters.PropertyA" />
但这会导致以下运行时异常:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 未处理的异常呈现组件:提供的表达式包含不受支持的 InvocationExpression1。 FieldIdentifier 仅支持简单的成员访问器(字段、 对象的属性)。 System.ArgumentException:提供的 表达式包含不受支持的 InvocationExpression1。 FieldIdentifier 仅支持简单的成员访问器(字段、 对象的属性)。在 Microsoft.AspNetCore.Components.Forms.FieldIdentifier.ParseAccessor[String](Expression`1 访问器、对象和模型、字符串和字段名)在 Microsoft.AspNetCore.Components.Forms.FieldIdentifier.Create[String](Expression`1 存取器)在 Microsoft.AspNetCore.Components.Forms.ValidationMessage`1[[System.String, System.Private.CoreLib,版本=5.0.0.0,文化=中性, PublicKeyToken=7cec85d7bea7798e]].OnParametersSet() 在 Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync() 在 Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
【问题讨论】:
-
如果属性是
Expression<Func<TValue>>类型,你为什么要尝试将Func<TValue>传递给它?不应该只是public Expressiona<Func<string>> PropertyLocator { get; set; }吗? -
请注意
public partial class MyComponent<TParam> { [Parameter] public TParam Parameters { get; set; } [Parameter] public Func<TReportParam, string> PropertyLocator { get; set; } }不能编译。TReportParam来自哪里?
标签: c# validation blazor blazor-webassembly