In the world of MVC I have this view model...
public class MyViewModel{
[Required]
public string FirstName{ get; set; } }
...and this sort of thing in my view...
<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>
My question: If I submit this form without supplying a name, I get the following message "The FirstName field is required"
OK. So, I go and change my property to...
[DisplayName("First Name")]
[Required]
public string FirstName{ get; set; }
..and now get "The First Name field is required"
All good so far.
So now I want the error message to display "First Name Blah Blah". How can I override the default message to display DisplayName + " Blah Blah", wihtout annotating all the properties with something like
[Required(ErrorMessage = "First Name Blah Blah")]
Cheers,
ETFairfax
You can use the standard ASP.NET MVC ValidationSummary method to render a placeholder for the list of validation error messages. The ValidationSummary() method returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
ASP.NET MVC: ValidationMessageFor ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object. Visit MSDN to know all the overloads of ValidationMessageFor() method.
The ValidationSummary can be used to display all the error messages for all the fields. It can also be used to display custom error messages.
public class GenericRequired: RequiredAttribute
{
public GenericRequired()
{
this.ErrorMessage = "{0} Blah blah";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With