I'm validating about 10 input fileds in a form. The ValidationMessageFor-tags should be at the top of the page, so I'm writing every one like:
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.NAME)
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.CITY)
and so on. My Models look like this:
[Required(ErrorMessage = Constants.ErrorMsgNameMissing)]
public string NAME { get; set; }
[Required(ErrorMessage = Constants.ErrorMsgCityMissing)]
public string CITY { get; set; }
The constants are Strings.
Now, if more than one ValidationMessageFor is shown, they are all in one line.
How can I insert a line break like <br />
at the end of every message?
This is NOT the right way:
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.NAME)<br />
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.CITY)<br />
since the <br />
is shown even if there is no error...;)
Thanks in advance.
PS: Displaying them as a list would also be great.
The Html. ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object.
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.
The ValidationSummary() extension method displays a summary of all validation errors on a web page as an unordered list element. It can also be used to display custom error messages.
I think what you're actually looking for is:
@Html.ValidationSummary()
I would go with @Html.ValidationSummary() if possible
Check out Custom ValidationSummary template Asp.net MVC 3. I think it would be best for your situation if you had complete control over how the validation is rendered. You could easily write an extension method for ValidationMessageFor
.
Actually, at the top should be:
@Html.ValidationSummary(/*...*/)
The field validations should be with their respective fields.
However, if you absolutely insist on putting @Html.ValidationMessageFor(/*...*/)
at the top then adjust their layout behavior in your CSS and forget about the <br />
's
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