1

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

2
  • Refer to this docs,and add services.AddMvc().AddDataAnnotationsLocalization() to your startup.cs, Commented Mar 16, 2020 at 8:19
  • Already look that but I want to use more than one shared resource (see my comment below) Commented Mar 16, 2020 at 12:09

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer but my question is : how can I use the same resource file for multiple viewmodels (ex : CreateUserViewModel, EditUserViewModel). The viewmodels based on the same entity share many validations so I want to reuse my messages. This is what I want to accomplish.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.