如何更改MVC验证错误信息 [英] How to change validation error messages in MVC
问题描述
您好我一直在试图改变验证错误消息(MVC3),并阅读了大量的线程,并从<一个发现href=\"http://stackoverflow.com/questions/6214066/how-to-change-default-validation-error-message-in-asp-net-mvc/6214961\">this螺纹:
Hi I've been trying to change the validation error messages (in MVC3) and read a lot of threads and find out from this thread:
- 为您的项目创建文件夹App_GlobalResources文件(单击鼠标右键结果
项目 - >添加 - >添加文件夹ASP.NET - > App_GlobalResources文件) - 添加RESX文件文件夹中。说MyNewResource.resx。
- 添加资源键PropertyValueInvalid与所需的信息
格式(例如,内容{0}是现场无效{1})。如果你想
改变PropertyValueRequired也添加它。 - 添加code DefaultModelBinder.ResourceClassKey =MyNewResource来
您的Global.asax启动code。
但我不能使它工作。这是一个干净的MVC 3 web应用程序我想改变验证消息。请为我的工作,并为其他人的样本。
But I cannot make it work. Here is a clean MVC 3 web application I want to change the validation messages. Please make it work for me as and as a sample for everybody else.
的这里是的链接,我的测试项目
here is the link for my test project
推荐答案
一些搜索和反复试验之后,我使用了一些code根据<一个href=\"http://thatextramile.be/blog/2011/04/customizing-asp-net-mvcs-required-property-validation-messages/\"相对=nofollow>这个博客帖子。改编低于code。
After some searching and trial and error, I used some code based on this blog post. Adapted code below.
添加一个新类到您的项目:
Add a new class to your project:
using System.Web.Mvc;
public class FixedRequiredAttributeAdapter : RequiredAttributeAdapter
{
public FixedRequiredAttributeAdapter (ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
: base(metadata, context, attribute)
{
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
// set the error message here or use a resource file
// access the original message with "ErrorMessage"
var errorMessage = "Required field!":
return new[] { new ModelClientValidationRequiredRule(errorMessage) };
}
}
告诉MVC在不断变化的应用程序开始使用此适配器 global_asax
:
protected void Application_Start()
{
...
DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(
typeof(RequiredAttribute),
(metadata, controllerContext, attribute) => new FixedRequiredAttributeAdapter(
metadata,
controllerContext,
(RequiredAttribute)attribute));
还有更多,你可以用错误信息做,如从资源文件中获取基于类/属性:
There's more you could do with the error message such as getting from a resource file based on the class/property:
var className = Metadata.ContainerType.Name;
var propertyName = Metadata.PropertyName;
var key = string.Format("{0}_{1}_required", className, propertyName);
测试了MVC5。
Tested with MVC5.
更新:看起来这只是作品的JavaScript /不显眼的验证。如果您关闭JavaScript回去后验证,它仍然显示,则需要{}田。
Update: Looks like this only works for javascript/unobtrusive validation. If you turn off javascript to get post-back validation, it still shows the "The {} field is required".
这篇关于如何更改MVC验证错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!