簡體   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