1
votes

In "classic" ASP.Net MVC, we could use data annotation properties ErrorMessageResourceName and ErrorMessageResourceType to specify which resource file should be used to localize the message of the annotation. I've seen a lot of posts and articles showing how to use a shared resource file in ASP.Net Core but how can I do this if I have multiple shared resources (for example, UserMessages.resx for my user view models and ProductMessages.resx for my product view models). Is there a way to use the IStringLocalizerFactory so multiple resource files can be used (and also, how to specify which one to use in case of key duplication) ?

Thanks

1
Refer to this docs,and add services.AddMvc().AddDataAnnotationsLocalization() to your startup.cs, - Rena
Already look that but I want to use more than one shared resource (see my comment below) - mberube.Net

1 Answers

1
votes

Here is a working demo like below:

1.Model:

public class UserModel
{
    [Required(ErrorMessage = "The Name field is required.")]
    [Display(Name = "Name")]

    public string Name { get; set; }
}
public class ProductModel
{
    [Required(ErrorMessage = "The Name field is required.")]
    [Display(Name = "Name")]

    public string Name { get; set; }
}

2.View:

@model UserModel   
@*for ProductModel's view,just change the @mdoel*@
@*@model ProductModel*@

<form asp-action="TestUser">
    <div>
        <div class="form-group">
            <label asp-for="Name" class="control-label"></label>
            <input asp-for="Name" class="form-control" />
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
        <div class="form-group">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </div>
</form>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

3.Startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        services.AddControllersWithViews().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
            opts => { opts.ResourcesPath = "Resources"; })
            .AddDataAnnotationsLocalization();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("fr"),
        };

        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US"),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures
        });
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

4.Resources file:

Location

enter image description here

UserModel resource file content: enter image description here

ProductModel resource file content: enter image description here

5.Result: enter image description here