![](/img/trans.png)
[英]Localizing Error Messages In ASP.NET MVC 2 (Default Validation Attributes)
[英]ASP.NET MVC Localizing or Changing Default Model Binding Error Messages
如何更改“值'某些值'对'某些属性'无效”验证错误的语言?
任何人都可以帮忙吗? 我想将图片中的错误翻译成俄语错误。 我阅读了很多网站,尝试使用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
注册它。
为此,请按照下列步骤操作:
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 Core,请阅读这篇文章: ASP.NET Core 模型绑定错误消息本地化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.