I'm using the MudTextField Component with in a generic Razor component.
In my case TValue will be used a with a string Type.
All other parameters for the MudTextfield will be provided from an custom helper class DataField which works well and should not bother you.
Now I started to implement FluentValidation on my generic text field component.
But it seems that I'm not able to declare an correct Expression which can be used with the For parameter.
<MudTextField T="TValue"
@bind-Value="(DataField.ValueBinder<TValue>().Value)"
Immediate="true"
Label="@DataField.Caption"
For = "@(() => MemberExpression())"/>
private Expression<Func<TValue>> MemberExpression()
{
return Expression.Lambda<Func<TValue>>(Expression.Property(Expression.Constant(Record), DataField.Name))
}
If I invoke the Expression manually I can see that it works correct.
MemberExpression().Compile().Invoke(); //returns the value of the property
When the validation is performed no propertyName ist passed to my validation method
public class ModelValidatorBase<TModel> : AbstractValidator<TModel>
{
public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
{
var result = await ValidateAsync(ValidationContext<TModel>.CreateWithOptions((TModel)model, x => x.IncludeProperties(propertyName)));
if (result.IsValid)
return Array.Empty<string>();
return result.Errors.Select(e => e.ErrorMessage);
};
}
If I declare the Expression directly in my razor file everything works correct
e.g.: For ="@(() => MyDataRecord.MyFieldName)"
So the challenge seems to declare an For-Expression dynamically so that it can be used with FluentValidation. Even my Expression works well, it makes troubles in combination with my validation class. Due to the correct validation result, when I directly apply the For parameter points out that there must be something wrong with my declaration of the MemberExpression() method - even if it returns the same result. Any ideas how the it can be dynamically specified?
Please take a look on the linked example I've just put on TryMudBlazor