8

I have view with the following which works:

<%= Html.TextBoxFor(m => m.FirstName, new { @class = "required_field_light" }) %>
<%= Html.ValidationMessageFor(m => m.FirstName) %>

However, if I change the ValidationMessageFor() to a ValidateFor() like this:

<%= Html.ValidateFor(m => m.FirstName) %>

I get this compile error:

"The best overloaded method match for 'System.IO.TextWriter.Write(char)' has some invalid arguments"
"Argument '1': cannot convert from 'void' to 'char'"

I assume I am missing something somewhere but I cannot figure out what it is. Has anyone else encountered this problem and found a solution, or does somebody have an idea how to resolve this?

Sailing Judo
  • 11,083
  • 20
  • 66
  • 97

2 Answers2

13

Since ValidateFor() returns void, call it like so:

<% Html.ValidateFor(m => m.FirstName); %>

(Note no equal sign; addition of semicolon.)

Levi
  • 32,628
  • 3
  • 87
  • 88
6

For those of you using Razor, you can do the same with

@{ Html.ValidateFor(x => x.FirstName); }

instead of the usual

@Html.ValidateFor(x => x.FirstName)

Again, as was mentioned by Levi, because a ValidateFor returns void, not MvcHtmlString like most Html. methods. And on that note, having no clue about what you're doing, if you're trying to use Html.ValidateFor I'd bet that you actually want to use:

@Html.ValidationMessageFor(x => x.FirstName)
Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
  • Your last code snippet, I think you mean @Html.ValidationMessageFor(x => x.FirstName) – GMon Feb 08 '17 at 21:46