We all know the lack of ViewModel localization in Blazor
Today i tried many ways, and i came up with a good method to be followed to apply localization
DataAnnotations
validation is probably not the best way to achieve this as the validation logic is tied to the class, and as you saw in your own answer, it means a lot of duplication.
FluentValidation provides an answer since it actually has built-in localization support (it also has built-in messages in many languages for default validations!).
I created a demo project on GitHub to show how it works.
As you can see this solution is a lot simpler.
public abstract class ProductViewModelBase { public virtual string ProductCode { get; set; } public virtual string ProductType { get; set; } public virtual string ProductName { get; set; } }
public class ProductViewModelAR : ProductViewModelBase { [Required(ErrorMessage = "خطأ")] public override string ProductCode { get; set; } } public class ProductViewModelEN : ProductViewModelBase { [Required(ErrorMessage = "Error")] public override string ProductCode { get; set; } }
ProductViewModelBase ViewModel; protected override void OnInitialized() { if (CultureInfo.CurrentUICulture.Name == "ar-EG") { ViewModel = new ProductViewModelAR(); } else { ViewModel = new ProductViewModelEN(); } }
And Now you can use this ViewModel in your EditForm
<EditForm Model="ViewModel" OnValidSubmit="ValidSubmit" OnInvalidSubmit="InValidSubmit"> <DataAnnotationsValidator /> <ValidationSummary /> </EditForm>
And in Run-time the app will decide which ViewModel version to load based on the selected language