asp.net-mvc 如何更改 ASP.NET MVC 中的默认验证错误消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6214066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change default validation error message in ASP.NET MVC?
提问by Sedat Kapanoglu
Say I have this property in my model:
假设我的模型中有这个属性:
[DisplayName("test")]
[Required(ErrorMessage = "required")]
public DateTime? SomeDate { get; set; }
when you type in "asdf" in Html.TextBoxFor(model => model.SomeDate)
, you get the validation error message "The value 'asdf' is not valid for test.".
当您在 中键入“asdf”时Html.TextBoxFor(model => model.SomeDate)
,您会收到验证错误消息“值‘asdf’对测试无效。”。
How do you modify that message? ASP.NET MVC ignored [DataType(DataType.DateTime, ErrorMessage = 'some other message')]
您如何修改该消息?ASP.NET MVC 被忽略[DataType(DataType.DateTime, ErrorMessage = 'some other message')]
采纳答案by Sedat Kapanoglu
Apparently my question was already answered at How to replace the default ModelState error message in Asp.net MVC 2?.
显然我的问题已经在How to replace the default ModelState error message in Asp.net MVC 2? .
I'll summarize it here:
我在这里总结一下:
- Create App_GlobalResources folder for your project (right click to project -> Add -> Add ASP.NET folder -> App_GlobalResources).
- Add a resx file in that folder. Say
MyNewResource.resx
. - Add resource key
PropertyValueInvalid
with the desired message format (e.g. "content {0} is invalid for field {1}"). If you want to changePropertyValueRequired
too add it as well. - Add the code
DefaultModelBinder.ResourceClassKey = "MyNewResource"
to your Global.asax startup code.
- 为您的项目创建 App_GlobalResources 文件夹(右键单击项目 -> 添加 -> 添加 ASP.NET 文件夹 -> App_GlobalResources)。
- 在该文件夹中添加一个 resx 文件。说
MyNewResource.resx
。 - 添加
PropertyValueInvalid
具有所需消息格式的资源键(例如“内容 {0} 对字段 {1} 无效”)。如果你也想改变,PropertyValueRequired
也添加它。 - 将代码添加
DefaultModelBinder.ResourceClassKey = "MyNewResource"
到您的 Global.asax 启动代码。
You're all set.
你都准备好了。