【问题标题】:ASP.NET MVC Localizing or Changing Default Model Binding Error MessagesASP.NET MVC 本地化或更改默认模型绑定错误消息
【发布时间】:2018-12-30 13:04:10
【问题描述】:

如何更改“The value 'some value' is not valid for 'some property'”验证错误的语言?

有人可以帮忙吗?我想把图片中的错误翻译成俄语Error。我阅读了很多网站,尝试使用RegularExpression,但它没有帮助 可能是我不正确理解如何做到这一点?

我只需要翻译错误,不需要改变文化。

在 web.config 中:

<globalization culture="en" uiCulture="en" />

我的具有数据注释属性的实体:

public class Player
{
    /* Some other properties */

    [Required(ErrorMessage = "Укажите среднее количество блокшотов")]
    [Range(0, 10.0, ErrorMessage = "Недопустимое значение, до 10")]
    public float BlockPerGame { get; set; }

    /* Some other properties */
}

我的看法:

@using (Html.BeginForm())
{
    @Html.HiddenFor(m => m.Id)    
    <div class="box-form">

    /* Some other properties */

    <div class="text-style-roboto form-group">
        <label>Среднее количество блокшотов</label>
        @Html.TextBoxFor(m => m.BlockPerGame, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.BlockPerGame)
    </div>

    /* Some other properties */

    <div class="form-group">
        <button type="submit" class="button button-create" id="button-create">Добавить</button>

        @Html.ActionLink("Отмена", "Index", null, new { @class = "button button-cancel", id = "button-cancel" })
    </div>
</div>
}

还有我的控制器:

public class AdminController : Controller
{
    /*Some other methods*/
    [HttpPost]
    public async Task<ActionResult> Edit(Player player, string ChoosingTeam)
    {
        if (ModelState.IsValid)
        {
            if (ChoosingTeam != string.Empty)
            {
                try
                {
                    player.TeamId = int.Parse(ChoosingTeam);
                    await repository.SavePlayerAsync(player);
                    TempData["message"] = string.Format("Игрок {0} {1} сохранены", player.Name, player.Surname);

                    return RedirectToAction("Index");
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                }
            }
        }
        IEnumerable<SelectListItem> list = new SelectList(repository.Teams, "Id ", "Name");
        ViewBag.ChoosingTeamName = list;
        return View(player);
    }
}

【问题讨论】:

  • 您输入的浮点数无效(您使用 ',' 而不是 '.' 作为分隔符)。如果您使用 [RegularExpression] 而不是浮点数作为数据类型的字符串怎么办?通过这种方式,您可以添加自定义错误消息

标签: c# asp.net-mvc validation localization model-binding


【解决方案1】:

当您为属性输入无效值时,如果模型绑定器无法将该值绑定到该属性,则模型绑定器会为该属性设置一条错误消息。它与数据注释模型验证不同。这实际上是模型绑定器验证错误。

本地化或更改默认模型绑定错误消息

模型绑定错误消息与模型验证消息不同。要对其进行自定义或本地化,您需要创建一个全局资源并将其注册到Application_Start 以供DefaultModelBinder.ResourceClassKey 使用。

为此,请按以下步骤操作:

  1. 转到解决方案资源管理器
  2. 右键项目→添加ASP.NET文件夹→选择App_GlobalResources
  3. 右击App_GlobalResources → 选择添加新项目
  4. 选择资源文件并将名称设置为ErrorMessages.resx
  5. 在资源字段中,添加以下键和值并保存文件:
    • PropertyValueInvalid: The value '{0}' is not valid for {1}.
    • PropertyValueRequired:A value is required.

注意:如果您只想自定义消息,则不需要任何特定语言的资源,只需在 ErrorMessages.resx 中编写自定义消息并跳过下一步。

  1. 如果您想要本地化,对于每种文化,复制资源文件并将其粘贴到同一文件夹中,然后将其重命名为 ErrorMessages.xx-XX.resx。而不是xx-XX 使用文化标识符,例如fa-IR 用于波斯语 并为这些消息输入翻译,例如 ErrorMessages.fa-IR.resx

    • PropertyValueInvalid: مقدار '{0}' برای '{1}' معتبر نمی باشد.
    • PropertyValueRequired:وارد کردن مقدار الزامی است.
  2. 打开 Global.asax 并在 Application_Start 中粘贴代码:

    DefaultModelBinder.ResourceClassKey = "ErrorMessages";
    

ASP.NET 核心

对于 ASP.NET Core,请阅读这篇文章:ASP.NET Core Model Binding Error Messages Localization

【讨论】:

  • 不翻译 1) 我创建 ErrorMasseges.ru-RU.resx 2)Name: PropertyValueInvalid ;值:Значение '{0}' записано не верно в {1}。名称:PropertyValueRequired;值:Значение пропущено 3) 在 global.asax 添加 DefaultModelBinder.ResourceClassKey = "ErrorMessages";我有同样的英文错误,我尝试 fa-IR 它不翻译
  • 因为您的应用程序的文化仍然是中性文化。对你来说,因为我看到你甚至在中立文化中也使用俄语错误消息,所以只需在 ErrorMasseges.resx 中使用俄语消息。忘记ErrorMasseges.ru-RU.resx
  • 确保您已经在App_GlobalResources 中创建了资源文件并按照我之前的评论进行操作。据我所知,您没有对验证属性使用本地化,因此中性文化的单个资源文件就足够了。
  • 我的错误对不起,它的工作,非常感谢你!!!真的有帮助!我删除了 ru-Ru,它起作用了
猜你喜欢
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
  • 2011-09-23
相关资源
最近更新 更多