How to add ViewModel localization to Blazor?

后端 未结 2 956
遇见更好的自我
遇见更好的自我 2021-01-07 03:54

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

相关标签:
2条回答
  • 2021-01-07 04:51

    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.

    0 讨论(0)
  • 2021-01-07 04:55
    • You can create an abstract base ViewModel for all properties for example “ProductViewModelBase“
    • Then makes all of your ViewModelBase Properties as virtual
     public abstract class ProductViewModelBase
     {
                   public virtual string ProductCode { get; set; }
                   public virtual string ProductType { get; set; }
                   public virtual string ProductName { get; set; }
     }
    
    • Then for your ViewModel languages override any property and add your specific language message and validation rules.
      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; }
        }
    
    • In your Blazor component, check which ViewModel to load
    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

    0 讨论(0)
提交回复
热议问题