10

I would like to change the htmlAttributes of the code rendered by my Html.ValidationMessageFor, but I want the message displayed to be the "default".

The overload options are:
A) Html.ValidationMessageFor(expression)
B) Html.ValidationMessageFor(expression, validationMessage)
C) Html.ValidationMessageFor(expression, validationMessage, htmlAttributesObject)

I wish there was a Html.ValidationMessageFor(expression, htmlAttributesObject) option, but there is not.

How can I achieve the desired result with option C? That is, where is that "default" messages stored? Is there an clean, easy way to get at it, so I can plug it in to the validationMessage parameter?

Thanks

1 Answer 1

19

Since you don't want to override the default message, simply supply an empty string and MVC will use the default message:

<%: Html.ValidationMessageFor(m => m.propertyName, string.Empty, new { attribs ... }) %>
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect. Thanks. I guess I assumed passing an empty string would render (or not, as it were) an empty string for the message. Is the fact that empty strings as parameters won't override a helper default some sort of ASP.NET or more general .NET convention? Or is that behavior variable on a case-by-case basis?
Neither really. I found out about this functionality by looking at the source code, Its worth looking when you get the chance. Its been done this way because there couldn't be a separate method just taking the two parameters you were originaly wanting to use, without the method signature clashing with (expression, validationMessage).
how do I pass in the HTMLAttribute (3rd param) to tell it to show this validation on a new line or under the field it is validing?
Either include a line break (<br>) in your error message, or simply include the ValidationMessage in a separate lien within your page markup

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.