我在我的 ASP.NET MVC 應用程式中使用可移植物件本地化。
我需要將引數傳遞給翻譯字串,例如
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;
}
}
如何將“組織名稱”作為引數傳遞給翻譯?
uj5u.com熱心網友回復:
該[Required]
屬性已經支持引數化錯誤訊息。事實上,默認的英文錯誤資訊是:
The {0} field is required.
在構造訊息時,它將使用屬性的來Name
[Display]
填充該引數。如果您沒有指定顯式顯示名稱,則默認使用屬性名稱。
"The Location field is required"
因此,以下屬性設定將在未設定值時提供錯誤訊息:
[Display(Name = "Location")]
[Required(ErrorMessage = "The {0} field is required")]
public string Location{ get; set; }
Display 和 Required 屬性(以及其他驗證屬性)的文本值都可以通過資源提供,因此您也可以將其推廣到多種語言,而無需在屬性中指定實際字串。
uj5u.com熱心網友回復:
首先,您需要"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; }
注意$
字串之前的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/506682.html