簡體   English   中英

使用 ASP.Net Core 進行數據注釋本地化

[英]Data annotation localization with ASP.Net Core

在“經典”的 ASP.Net MVC 中,我們可以使用數據注釋屬性ErrorMessageResourceNameErrorMessageResourceType來指定應該使用哪個資源文件來本地化注釋的消息。 我看過很多帖子和文章,展示了如何在 ASP.Net Core 中使用共享資源文件,但是如果我有多個共享資源(例如,用戶視圖模型的 UserMessages.resx 和 ProductMessages.resx.我的產品視圖模型的 resx)。 有沒有辦法使用 IStringLocalizerFactory 以便可以使用多個資源文件(以及如何指定在密鑰重復的情況下使用哪個)?

謝謝

這是一個如下所示的工作演示:

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.資源文件:

地點

在此處輸入圖片說明

UserModel 資源文件內容: 在此處輸入圖片說明

ProductModel資源文件內容: 在此處輸入圖片說明

5.結果: 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM