Search code examples
c#asp.netasp.net-corerazor

How to read the string values of multiple Language class files , Razor pages .net-core 7.0 frontend?


1.Explaination

I have the login page, which is in English. I have created an Italian language class where i have inserted the public string translations.

If i want to call only the italian language values inside the class, it works flawlessly.

What i want is:

to click a button which has an asp-route-id="1" for english, or an asp-route-id="2" for italian.

After click, the page reads the english or italian language class values and shows them in the frontend.

On the backend, 'gg' is declared as an [TempData] public int gg {get; set;}.

if i declare only the: LanguageEnglishExtensions lang = new(); in the frontend, i can retrieve the class values correctly.

The same works for the Italian too, without an if{}else{} declaration.

Ps: I know that there is a solution with resources, but, to me, this seems more direct and simple to reach what i want.

2.Question

How can this be done to make it work?

3.The frontend C# code (not working)

@{

@if (gg <= 1 || gg.ToString() == null)
{
  LanguageEnglishExtensions lang = new();
}
else
{
     LanguageItalianExtensions lang = new();
}

4.The frontend Html code

 <form id="account" method="post">
 <a asp-page="/Connect" asp-route-id="1" class=" btn btn-outline-primary">
   EN
</a>

<a asp-page="/Connect" asp-route-id="2" class=" btn btn-outline-primary">
   IT
</a>
 <div asp-validation-summary="All" class="text-danger"></div>
 <div class="form-floating">
         <input asp-for="Input.Email" class="form-control" autocomplete="username" aria-required="true" />
         <label asp-for="Input.Email" class="form-label">@lang.email</label>
         <span asp-validation-for="Input.Email" class="text-danger"></span>
     </div>
     <div class="form-floating">
         <input asp-for="Input.Password" class="form-control" autocomplete="current-password" aria-required="true" style="text-align:center;" />
         <label asp-for="Input.Password" class="form-label">@lang.password</label>
         <span asp-validation-for="Input.Password" class="text-danger"></span>
     </div>
     <div class="form-group text-center">
     <br>
     <button type="submit" class="btn btn-outline-primary  border-light" >
             &ensp; @lang.login
     </button>
      </div>
 </div>

5.The Italian Language class

public  class LanguageItalianExtensions

{

public  string email = "Indirizzo email";
public  string password = "Password";
 public  string login = "Entra";

}


Solution

  • You could check the document related with localization in asp.net core

    Register required services and call middleware in program.cs:

    builder.Services.AddRazorPages().AddViewLocalization();
    builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
    var enUSCulture = "en-us";
    builder.Services.Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new[]
        {
            new CultureInfo(enUSCulture),
            new CultureInfo("it-it")
        };
        options.DefaultRequestCulture = new RequestCulture(culture: enUSCulture, uiCulture: enUSCulture);
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;
    
    });
    

    ....

    app.UseRequestLocalization();
    

    Add sharedresource follow this part of document:

    enter image description here

    enter image description here

    Create a partial view to select language:

    @using Microsoft.AspNetCore.Builder
    @using Microsoft.AspNetCore.Http.Features
    @using Microsoft.AspNetCore.Localization
    @using Microsoft.AspNetCore.Mvc.Localization
    @using Microsoft.Extensions.Options
    
    @inject IViewLocalizer Localizer
    @inject IOptions<RequestLocalizationOptions> LocOptions
    
    @{
        var requestCulture = Context.Features.Get<IRequestCultureFeature>();
        var cultureItems = LocOptions.Value.SupportedUICultures
            .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
            .ToList();
        var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
    }
    
    <div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
        <form id="selectLanguage" 
              asp-page="Index" asp-page-handler="SelectLanguage" asp-route-returnUrl="@returnUrl"
              method="post" class="form-horizontal" role="form">
            <label asp-for="@requestCulture.RequestCulture.UICulture.Name">@Localizer["Language:"]</label> <select name="culture"
                                                                                                                   onchange="this.form.submit();"
                                                                                                                   asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">
            </select>
        </form>
    </div>
    

    Call the partial view in layout so that we could selct language in every page:

    <div class="col-md-6 text-right">
        @await Html.PartialAsync("_SelectLanguagePartial")
    </div>
    

    Add a handler in Index page:

    public IActionResult OnPostSelectLanguage(string culture, string returnUrl)
     {
         Response.Cookies.Append(
             CookieRequestCultureProvider.DefaultCookieName,
             CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
             new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
         );
    
         return LocalRedirect(returnUrl);
     }
    

    Account Page:

    @inject IHtmlLocalizer<SharedResource> SharedLocalizer
    
    
     <form id="account" method="post">
        
     <div asp-validation-summary="All" class="text-danger"></div>
     <div class="form-floating">
             <input asp-for="Input.Email" class="form-control" autocomplete="username" aria-required="true" />
            <label asp-for="Input.Email" class="form-label">@SharedLocalizer["email"]</label>
             <span asp-validation-for="Input.Email" class="text-danger"></span>
         </div>
         <div class="form-floating">
             <input asp-for="Input.Password" class="form-control" autocomplete="current-password" aria-required="true" style="text-align:center;" />
            <label asp-for="Input.Password" class="form-label">@SharedLocalizer["password"]</label>
             <span asp-validation-for="Input.Password" class="text-danger"></span>
         </div>
         <div class="form-group text-center">
         <br>
         <button type="submit" class="btn btn-outline-primary  border-light" >
                @SharedLocalizer["login"]
         </button>
          </div>
     </div>
     <</form>
    

    Result:

    enter image description here

    Upon your comment:

    public class LanguageExtensions
    {
    
        public string email ;
        public string password ;
        public string login ;
    }
    public class LanguageItalianExtensions : LanguageExtensions
    {
        public LanguageItalianExtensions()
        {
           login= "Entra";
           email = "Indirizzo email";
           password = "Password";
        }
    }
    public class LanguageEnglishExtensions : LanguageExtensions
    {
        public LanguageEnglishExtensions()
        {
            login = "Login";
            email = "Email";
            password = "Password";
        }
    }
    

    Page Model:

    public class AccountModel : PageModel
    {
        [BindProperty]
        public InputModel? Input { get; set; }
        [BindProperty]
        public LanguageExtensions lang { get; set; } = new LanguageEnglishExtensions();
    
        public void OnGet()
        {
        }
    
        public void OnGetSelectLanguage(int Id)
        {
            if(Id==2)
            {
                lang = new LanguageItalianExtensions();
            }
            else
            {
                lang = new LanguageEnglishExtensions();  
            }
        }
    
    }
    

    cshtml:

     <form id="account" method="post">
        <a asp-page="/Account" asp-page-handler="SelectLanguage" asp-route-id="1" class=" btn btn-outline-primary">
            EN
        </a>
    
        <a asp-page="/Account" asp-page-handler="SelectLanguage" asp-route-id="2" class=" btn btn-outline-primary">
            IT
        </a>
        
     <div asp-validation-summary="All" class="text-danger"></div>
     <div class="form-floating">
             <input asp-for="Input.Email" class="form-control" autocomplete="username" aria-required="true" />
            <label asp-for="Input.Email" class="form-label">@Model.lang.email</label>
             <span asp-validation-for="Input.Email" class="text-danger"></span>
         </div>
         <div class="form-floating">
             <input asp-for="Input.Password" class="form-control" autocomplete="current-password" aria-required="true" style="text-align:center;" />
            <label asp-for="Input.Password" class="form-label">@Model.lang.password</label>
             <span asp-validation-for="Input.Password" class="text-danger"></span>
         </div>
         <div class="form-group text-center">
         <br>
         <button type="submit" class="btn btn-outline-primary  border-light" >
                @Model.lang.login
         </button>
          </div>
     </div>
     <</form>
    

    Result:

    enter image description here