我如何在 cshtml 中为 @Html.DisplayNameFor(model => model....) 使用 Localizer

问题描述

我想在我的项目中添加多语言。我可以在 cshtml 中使用本地化,但我不能在 label 标签displaynamefor 标签中使用它。

我该如何使用它?

解决方法

您可以使用 Display 属性来本地化名称:

1.型号:

public class Test
{        
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

2.在MyReource.resx文件夹中创建名为Reources的资源文件:

enter image description here

3.在资源文件中创建键值:

注意: .resx 文件上的修饰符,默认设置为 Internal(在我的情况下是无代码生成)。在资源文件工具栏中的 Access Modifier 下拉菜单中将其更改为 public。

enter image description here

此外,请考虑不要在字段名称中使用特殊符号,因为它们是自动生成的 C# 属性名称的基础。字段名称转换为 C# 友好名称,这就是为什么您最终会出现资源文件字段名称和自动生成属性名称不一致的原因。最好避免使用任何连字符 - 或点 .。下划线 _ 很好。您可以随时在相关资源文件下的 resource_file_name.Designer.cs 类中查找自动生成的属性。

例如,您想在剃刀中将电子邮件属性显示为 Email Address,您需要设置的资源文件如下:

enter image description here

但是您可以看到 resource_file_name.Designer.cs 如下所示:

enter image description here

4.修改你的模型:

public class Test
{        
    public int Id { get; set; }
    [Display(Name = "Name",ResourceType = typeof(MyResource))]
    public string Name { get; set; }

    [Display(Name = nameof(MyResource.Email_Address),ResourceType = typeof(MyResource))]
    public string Email { get; set; }
}

5.Startup.cs:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        services.AddControllersWithViews()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();

        services.Configure<RequestLocalizationOptions>(
         opt =>
         {
             var supportCulteres = new List<CultureInfo>
             {
            new CultureInfo("en"),new CultureInfo("fr")
             };
             opt.DefaultRequestCulture = new RequestCulture("en");
             opt.SupportedCultures = supportCulteres;
             opt.SupportedUICultures = supportCulteres;
         });
    }

    public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
    {
        var options = app.ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(options.Value);

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

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

Index.cshtml:

@model Test
<div>
    @Html.DisplayNameFor(model => model.Name)
</div>
<div>
    @Html.DisplayNameFor(model => model.Email)
</div>
<div>
    @Html.LabelFor(model => model.Email)
</div>

结果:

enter image description here