1

I am a webform guy who wants to move to ASP.Net Core & Blazor I don't have any background in MVC just in case someone may give their feedback based on MVC.

I am interested in ASP.Net Core Razor page only.

In web form I use two files for a multilingual website, for example, I can keep related validation messages in .aspx page or in related js files if necessary, while in Core it does things differently. In webform I can keep validation message in .aspx file itself while in ASP.Net core I have been using Single Model class and Validation message is defined there.

Webform structure

-en
--index
--aboutus
..
..
-ar
--index
--aboutus

ASP.Net Core folder structure

Pages
-en
--index
--aboutus
..
..
-ar
--index
--aboutus

Let us say under Pages folder I create two folders one for English & another for Arabic and in Core we let us say I have defined my validation in Model file. Since I have one model file for both languages how can I show language specific validation message

Below code is just for example

using System;
using System.ComponentModel.DataAnnotations;

public class Starship
{
    [Required]
    [StringLength(16,
        ErrorMessage = "Identifier too long (16 character limit).")]
    public string Identifier { get; set; }

    public string Description { get; set; }

    [Required]
    public string Classification { get; set; }

    [Range(1, 100000,
        ErrorMessage = "Accommodation invalid (1-100000).")]
    public int MaximumAccommodation { get; set; }

    [Required]
    [Range(typeof(bool), "true", "true",
        ErrorMessage = "This form disallows unapproved ships.")]
    public bool IsValidatedDesign { get; set; }

    [Required]
    public DateTime ProductionDate { get; set; }
}

Problem i am facing since i have one Model file which have validation in English how can i show Validation in Arabic in most easy & simple way in ASP.Net core

Assuming my URL is like

www.example.com/en/ 
www.example.com/en/aboutus/ 
www.example.com/en/contact/

www.example.com/ar/ 
www.example.com/ar/aboutus/ 
www.example.com/ar/contact/

Can language based validation message shows just based on above URL without using any globalization feature for website pages which has any forms etc..

behzad
  • 801
  • 3
  • 15
  • 33
Learning
  • 19,469
  • 39
  • 180
  • 373

2 Answers2

3

Can language based validation message be show just based on above url without using any globalization feature for website pages which has any forms etc..

Yes validation messages can be shown with reference to the culture parameter in the route. But in order for the localization to work properly you need to do some setup.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddDataAnnotationsLocalization(options => {
            options.DataAnnotationLocalizerProvider = (type, factory) =>
                factory.Create(typeof(SharedResource));
        });
}

www.example.com/ar/contact/

Looking at the url, you need route data request culture provider. By default Asp.Net Core uses QueryString, Cookie and AccpetLanguageHeader culture providers (see the docs for more details), so if you want to use route value for localization you need to setup route data culture provider:

services.Configure<RequestLocalizationOptions>(ops =>
{
    ops.DefaultRequestCulture = new RequestCulture("en");
    ops.SupportedCultures = mySupportedCultures;
    ops.SupportedUICultures = mySupportedUICultures;

    // add RouteDataRequestCultureProvider to the beginning of the providers list. 
    ops.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider(cultures));
});

But thats not all! There is many other topics to consider for properly localizing Asp.Net Core web apps :

  • Views localization
  • DataAnnotations localization
  • ModelBinding errors localization
  • IdentityDescriber errors localization
  • Custom backend messages localization
  • Client side validation messages localization

You can read the official docs for Asp.Net-Core globalization and localization.

Additionally, I wrote some articles describing localization in detail, see Developing Multicultural Web Application.


how can i show Validation in Arabic in most easy & simple way in ASP.Net core

If you are looking for a fast and easy way you can use LazZiya.ExpressLocalization nuget package, it offers very simple way for all localization setup:

//add reference to :
using LazZiya.ExpressLocalization;

//setup express localization under ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
    //other configuration settings....

    var cultures = new CultureInfo[]
    {
        new CultureInfo("en"),
        new CultureInfo("tr"),
        new CultureInfo("ar")
    };

    services.AddRazorPages()
        //ExpressLocalizationResource and ViewLocalizationResource are available in :
        // https://github.com/LazZiya/ExpressLocalizationSample
        .AddExpressLocalization<ExpressLocalizationResource, ViewLocalizationResource>(
            exOps =>
            {
                exOps.ResourcesPath = "LocalizationResources";
                exOps.RequestLocalizationOptions = ops =>
                {
                    ops.SupportedCultures = cultures;
                    ops.SupportedUICultures = cultures;
                    ops.DefaultRequestCulture = new RequestCulture("en");
                };
            });
}

That is almost all what you need to setup the "express" localization. Here you can find a step by step tutorial for using ExpressLocalization and a sample github repository

LazZiya
  • 5,286
  • 2
  • 24
  • 37
  • I had previously looked at similar example where user was using LazZiya package.. it was too much for a starter in a way may be i need to look at it again to properly understand it & if it was work well for me. I avoided Location using Resource file in asp.net for Single .aspx for all language as its not practical over time as i had different design elements for different languages so best approach for me was using separate files for each language which took extra time but gave me flexibility so i want to take same approach in asp.net core as i want to convert same project to core – Learning Jan 02 '20 at 07:57
  • I noticed in your example you are using single file for different language while i want to use seperate files for different languages as pointed in my question.. Yes will need to use singel file for login authorization as pointed in your example. I wish you could touch base my scenario in your code example also.. – Learning Jan 02 '20 at 08:00
  • Technically and logically it is not correct to use one file for different languages! my sample already provides separate files for each language [see them here](https://github.com/LazZiya/ExpressLocalizationSampleCore3/tree/master/ExpressLocalizationSampleCore3/LocalizationResources). Additionally you may use [one resource file for each language](https://github.com/LazZiya/ExpressLocalization/blob/master/README.md#one-step-setup) or you can use [multiple resource files](https://github.com/LazZiya/ExpressLocalization/blob/master/README.md#customized-steps-optional) as described in the readme. – LazZiya Jan 02 '20 at 08:08
  • I am not talking about Resource files i am talking about Razor page Index, Aboutus, Contact etc.. Resource file need to be different for different language etc.. Your work is exceptional as so far i cant find any other resource – Learning Jan 02 '20 at 08:10
  • Okay, you mean the shared resource files :) actually yes, my sample is using shared resource files, so you don't have to create separate resources for each view. But you want to do so right? – LazZiya Jan 02 '20 at 08:15
  • btw, when using shared resource files it is easy to add new culture, all you need is just one more resource file. But if you are using separate resources for each view there will be more workload to add many resources for all the views in the project. Anyway, it is up to you to choose the way that fits your needs. – LazZiya Jan 02 '20 at 08:28
  • @Ziya, I am looking at your code https://github.com/LazZiya/ExpressLocalizationSampleCore3/tree/master/ExpressLocalizationSampleCore3 and want to know when i change language it also change url path exampl `/en/` to `/ar` where & how in code that is changed – Learning Jan 09 '20 at 10:43
  • well, when the language is changed the page is redirecting again to the same uri but with new culture selected. The [{culture} route template](https://github.com/LazZiya/ExpressLocalization/blob/master/LazZiya.ExpressLocalization/RouteTemplateModelConvention.cs) is already defined in ExpressLocalization to be the first parameter in the route. Then the [route culture provider](https://github.com/LazZiya/ExpressLocalization/blob/master/LazZiya.ExpressLocalization/RouteSegmentCultureProvider.cs) is detecting the current culture depeding on the {culture} route value. – LazZiya Jan 09 '20 at 10:59
1

Now you use this:

[Required]
[StringLength(16, ErrorMessage = "Identifier too long (16 character limit).")]
public string Identifier { get; set; }

But when you change to multilanguage you need to use like this:

[Required(ErrorMessageResourceType = typeof(MyProject.Resources.Starship),
      ErrorMessageResourceName = "IdentifierRequired")]
[StringLength(16, ErrorMessageResourceType = typeof(MyProject.Resources.Starship),
      ErrorMessageResourceName = "IdentifierLength")]
public string Identifier { get; set; }

In order to use this option, the classes associated with the referenced .resx resource files must be automatically generated. To do this, in the properties of the .resx file we must set its Custom tool property to ResXFileCodeGenerator or PublicResXFileCodeGenerator.

Anton Nikolayevich
  • 579
  • 1
  • 5
  • 19