在 ASP.Net MVC 5
View
中,当 View
中的控件/输入试图在数据库中创建列值(或 class
中的字段值),这应该是唯一的但我们违反了它 - 例如在使用现有电子邮件创建新用户帐户的电子邮件时,如下所示。
现在,我应该将上面的错误消息更改为我项目中的本地语言:
... is already taken <-> ... [is already taken in local language]
如何更改“[field value] already taken”(自动)错误信息?
根据这篇文章:
Issue with username validation message in asp.net identity
我们可以尝试在整个解决方案中搜索“名称 {0} 已被占用”,但当我这样做时,我找不到它。
在早期的 MVC
中这是一个有效的解决方案,但对于 MVC 5
来说已经过时了吗?
(注意:不幸的是,该帖子并未指明 OP 使用的是哪个 ASP.Net MVC 版本)
最佳答案
我已经通过使用 Remote 实现了这个在 System.ComponentModel.DataAnnotations
中。请引用以下代码:
在 ViewModel
(Properties
)中:
[Display(Name = "Email")]
[Remote("IsValidUserName", "Remote", AdditionalFields = "Email", HttpMethod = "Post")]
public string Email { get; set; }
这里“Remote”是一个 Controller
名称,“IsValidUserName”是我们的 Method
。如下所示:
public class RemoteController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult IsValidUserName()
{
string email= Request.Form["Email"];
string message = "Email '"+ email+ "' is already taken";
if (!string.IsNullOrEmpty(email))
{
using (DbContext db = new DbContext())
{
if (!db.tb_Users.Any(x => x.email== email))
{
message = string.Empty;
}
}
}
if (message == string.Empty)
return Json(true, JsonRequestBehavior.AllowGet);
else
return Json(message, JsonRequestBehavior.AllowGet);
}
}
在 View
页面上,您必须像下面这样使用它:
@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
要记住的要点:
您必须使用以下 JavaScript
来运行它:
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.jss"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
希望对你有帮助。
谢谢。
关于c# - 如何更改 ASP.Net MVC 5 中的默认 "[field value] already taken"错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38867208/