ASP.NET MVC 本地化或更改默认模型绑定错误消息
ASP.NET MVC Localizing or Changing Default Model Binding Error Messages
如何更改 "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);
}
}
当您为 属性 输入无效值时,如果模型绑定器无法将该值绑定到 属性,则模型绑定器会为该 属性 设置一条错误消息。它不同于数据注释模型验证。这实际上是模型活页夹验证错误。
本地化或更改默认模型绑定错误消息
模型绑定错误消息与模型验证消息不同。要自定义或本地化它们,您需要创建一个全局资源并在 Application_Start
中为 DefaultModelBinder.ResourceClassKey
注册它。
为此,请按照下列步骤操作:
- 转到解决方案资源管理器
- 右击项目→添加→ASP.NET文件夹→选择App_GlobalResources
- 右击App_GlobalResources → 选择添加新项目
- 选择资源文件并将名称设置为ErrorMessages.resx
- 在资源字段中,添加以下键和值并保存文件:
PropertyValueInvalid
: The value '{0}' is not valid for {1}.
PropertyValueRequired:
A value is required.
注意:如果您只想自定义消息,则不需要任何特定于语言的资源,只需在 ErrorMessages.resx
并跳过下一步。
如果要本地化,对于每种文化,复制资源文件并粘贴到同一文件夹中,重命名为ErrorMessages.xx-XX.resx 。而不是 xx-XX
使用文化标识符,例如 fa-IR
波斯语
并为这些消息输入翻译,例如 ErrorMessages.fa-IR.resx:
PropertyValueInvalid
: مقدار '{0}' برای '{1}' معتبر نمی باشد.
PropertyValueRequired:
وارد کردن مقدار الزامی است.
打开Global.asax并在Application_Start
中粘贴代码:
DefaultModelBinder.ResourceClassKey = "ErrorMessages";
ASP.NET核心
对于 ASP.NET 核心阅读此 post:。
如何更改 "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);
}
}
当您为 属性 输入无效值时,如果模型绑定器无法将该值绑定到 属性,则模型绑定器会为该 属性 设置一条错误消息。它不同于数据注释模型验证。这实际上是模型活页夹验证错误。
本地化或更改默认模型绑定错误消息
模型绑定错误消息与模型验证消息不同。要自定义或本地化它们,您需要创建一个全局资源并在 Application_Start
中为 DefaultModelBinder.ResourceClassKey
注册它。
为此,请按照下列步骤操作:
- 转到解决方案资源管理器
- 右击项目→添加→ASP.NET文件夹→选择App_GlobalResources
- 右击App_GlobalResources → 选择添加新项目
- 选择资源文件并将名称设置为ErrorMessages.resx
- 在资源字段中,添加以下键和值并保存文件:
PropertyValueInvalid
:The value '{0}' is not valid for {1}.
PropertyValueRequired:
A value is required.
注意:如果您只想自定义消息,则不需要任何特定于语言的资源,只需在 ErrorMessages.resx
并跳过下一步。
如果要本地化,对于每种文化,复制资源文件并粘贴到同一文件夹中,重命名为ErrorMessages.xx-XX.resx 。而不是
xx-XX
使用文化标识符,例如fa-IR
波斯语 并为这些消息输入翻译,例如 ErrorMessages.fa-IR.resx:PropertyValueInvalid
:مقدار '{0}' برای '{1}' معتبر نمی باشد.
PropertyValueRequired:
وارد کردن مقدار الزامی است.
打开Global.asax并在
Application_Start
中粘贴代码:DefaultModelBinder.ResourceClassKey = "ErrorMessages";
ASP.NET核心
对于 ASP.NET 核心阅读此 post: