Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

How to change default validation error message in ASP.NET MVC?

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.".

How do you modify that message? ASP.NET MVC ignored [DataType(DataType.DateTime, ErrorMessage = 'some other message')]

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Apparently my question was already answered at 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 change PropertyValueRequired too add it as well.
  • Add the code DefaultModelBinder.ResourceClassKey = "MyNewResource" to your Global.asax startup code.

You're all set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...