繁体   English   中英

如何将参数传递给 ASP.NET 核心 MVC .NET 6 中的本地化字符串?

[英]How to pass parameter to localization string in ASP.NET core MVC .NET 6?

我在我的 ASP.NET MVC 应用程序中使用便携式 Object 本地化。

我需要将参数传递给翻译字符串,例如

msgid "The {0} field is required"
msgstr[0] "موجودیت {0} لازمی میباشد"

我想为我的模型的每个必填字段使用上面的示例。


using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace aaeamis.Models
{
    public class OrganizationModel
    {
        public int OrganizationId { get; set; }
        // I want to pass "Organization Name" to translation
        [Required(ErrorMessage = "The Organization Name field is required")]
        public string OrganizationName { get; set; }
        // I want to pass "Location" to translation
        [Required(ErrorMessage = "The Location field is required")]
        public string Location{ get; set; }
        public int CreatedBy { get; set; }
        public DateTime CreatedAt { get; set; } = DateTime.Now;
        public DateTime CreatedAt { get; set; } = DateTime.Now;
    }
}

如何将“组织名称”作为参数传递给翻译?

[Required]属性已经支持参数化错误消息。 事实上,默认的英文错误信息是:

The {0} field is required.

在构造消息时,它将使用[Display]属性的Name来填充该参数。 如果您没有指定显式显示名称,则默认使用属性名称。

因此,当未设置值时,以下属性设置将提供错误消息"The Location field is required"

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

Display 和 Required 属性(以及其他验证属性)的文本值都可以通过资源提供,因此您也可以将其推广到多种语言,而无需在属性中指定实际字符串。

首先,您需要从变量本身获取字符串"OrganizationName"

var fieldName = nameof(OrganizationName)

然后,如果您使用的是 C# 10 (.NET 6.0),您可以使用const 字符串插值来设置错误消息。

[Required(ErrorMessage = $"The {nameof(OrganizationName)} field is require")]
public string OrganizationName { get; set; }

[Required(ErrorMessage = $"The {nameof(Location)} field is require")]
public string Location { get; set; }

注意字符串前的$

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM