Локализация аннотаций данных с ASP. Net Core - PullRequest
0 голосов
/ 15 марта 2020

В «classi c» ASP. Net MVC мы могли бы использовать свойства аннотации данных ErrorMessageResourceName и ErrorMessageResourceType , чтобы указать, какой файл ресурсов следует использовать локализовать сообщение аннотации. Я видел много постов и статей, показывающих, как использовать файл общих ресурсов в ASP. Net Core, но как я могу это сделать, если у меня есть несколько общих ресурсов (например, UserMessages.resx для моего пользователя) модели и ProductMessages.resx для моих моделей просмотра продукта). Есть ли способ использовать IStringLocalizerFactory, чтобы можно было использовать несколько файлов ресурсов (а также, как указать, какой из них использовать в случае дублирования ключа)?

Спасибо

1 Ответ

0 голосов
/ 16 марта 2020

Вот рабочая демонстрация, как показано ниже:

1.Модель:

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.Просмотр:

@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. Файл ресурсов:

Местоположение

enter image description here

Содержимое файла ресурса UserModel: enter image description here

Содержимое файла ресурса ProductModel: enter image description here

5 .Результат: enter image description here

...