I'm generating an object at runtime to use as the EditForm model. Validation is working but I'm unsure how to set up the ValidationMessage component which requires an Expression<Func<object>>.
I want to provide it with a property via reflection. Something like this:
<ValidationMessage For="@(() => modelType.GetProperty("MyString").GetValue(model))" />
How can I get an Expression from an object property generated at runtime?
EDIT:
Here is my code:
<EditForm Model="@GeneratedModel" OnInvalidSubmit="@HandleInvalidSubmit" OnValidSubmit="@OnValidSubmit">
<DataAnnotationsValidator />
<input @bind="TestPropBind" type="text" />
<ValidationMessage For="@ValidationFor" />
</EditForm>
@code
{
private object GeneratedModel { get; set; }
private string TestPropBind
{
get
{
PropertyInfo? propertyInfo = GeneratedModel.GetType().GetProperty("Test");
MethodInfo? getMethod = propertyInfo.GetGetMethod();
return getMethod.Invoke(GeneratedModel, new object?[0]) as string;
}
set
{
PropertyInfo? propertyInfo = GeneratedModel.GetType().GetProperty("Test");
MethodInfo? setMethod = propertyInfo.GetSetMethod();
setMethod.Invoke(GeneratedModel, new[] { value });
}
}
protected override void OnInitialized()
{
//GeneratedModel created and instantiated here at runtime
}
}
ValidationMessageis a fairly simple component. Internally it uses theForto build aFieldIdentifierobject which it uses to lookup validation messages in theEditContext'sValidation Message Store.You can shortcut the whole reflection/expression builder process by building your own
ValidationMessagethat takes aFieldIdentifieras a parameter:Your demo page: