簡體   English   中英

在 Asp.net 內核中本地化 DataAnnotations

[英]Localize DataAnnotations in Asp.net core

在我的 asp.net 核心 (.net5) 應用程序中,我有一個帶有必填字段的表單。 當該字段為空時,我有

在此處輸入圖像描述

“XX 字段是必填項”……英文……我想翻譯成法語。 我的意思是,我真的不想翻譯,我想使用法語版本的消息。 我不想添加資源文件,因為我有任何自定義字符串要翻譯,我只想使用現有的消息,但使用法語。

我開始在這里閱讀,但如果這篇文章真的建議我自己手動翻譯每條消息,我並沒有真正明白這一點。

我在配置中添加了這個

var supportedCultures = new[] { "fr-FR" };
var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supportedCultures[0])
    .AddSupportedCultures(supportedCultures)
    .AddSupportedUICultures(supportedCultures);

app.UseRequestLocalization(localizationOptions);

但這並沒有改變信息......

也不通過 URL 設置文化參數,像這樣

在此處輸入圖像描述

如果你只想要一個法語版本,你只需要在 [Required] 中定義錯誤信息

屬性,例如:

public class MyModel
{
    [Required(ErrorMessage = "Le champ Nom est obligatoire")]
    public string Nom { get; set; }
}

如果您的共享代碼引用了您共享的文檔,則需要將資源文件添加到

定義翻譯的消息,否則消息不會改變。

編輯:

如果你有其他屬性,你可以定義一個 customRequired 屬性:

 public class CustomRequiredAttribute : ValidationAttribute
{
    public CustomRequiredAttribute()
    {         
    }
    
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
        {
            ErrorMessage = $"Le champ {validationContext.DisplayName} est obligatoire";
            return new ValidationResult(ErrorMessage);
        }
        return ValidationResult.Success;
    }
}

Model:

public class MyModel
{   
    [CustomRequired]  //custom attribute
    public string Nom { get; set; }        
    [CustomRequired]
    public string PreNom { get; set; }
}

要使用您的自定義屬性,您應該在您的 post 操作中添加ModelState.IsValid ,因此如果無效,它將返回輸入視圖以顯示錯誤消息,例如:

[HttpPost]
    public IActionResult Privacy(MyModel myModel)
    {
        if (!ModelState.IsValid)
            return View("Index");
        return View();
    }

在此處輸入圖像描述

暫無
暫無

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

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