How Does Html.EnableClientValidation() Inject JavaScript?

Posted by on in Blogs
For a project I'm currently working on, I have a need to add some JavaScript at the end of a page in an ASP.NET MVC application. Since this is part of what Html.EnableClientValidation does, I thought that I would check out that source code to see if there was any kind of generalized mechanism for this. No such luck, I'm afraid. But I did learn a bit more about how Html.EnableClientValidation works, so I thought I might write that down in case it turned out to be useful someday.

The Html.EnableClientValidation method itself does almost nothing. It just sets a flag indicating that other methods which care about client validation should do their thing. The start of the sequence which concludes with client validation JavaScript being written into the HTML page begins with Html.EndForm. Most people don't call this directly, instead calling Html.BeginForm inside of a using block, which amounts to the same thing. Html.EndForm, in MVC 2 does two things:

  1. Writes a </form> closing tag. No surprise there.

  2. Writes client-side validation JavaScript.

Therefore, client-side validation will not work if you manually write a <form> tag rather than directly or indirectly calling Html.EndForm. However, you can look at its source code and do the same thing yourself if you prefer to write your own <form> tag.

If this second action is a little surprising for a method called "EndForm" the manner in which it accomplishes this task is even more surprising: It calls a function on the ViewContext type which knows how to write client validation JavaScript onto the page. Perhaps, like me, you've always thought of the ViewContext type as simply an aggregation of properties containing information relevant to the (ahem) context in which the current page is being rendered. Well, in addition to this, ViewContext also contains a method which writes JavaScript for client validation. It also contains a const with the hard-coded template for the final <script> tag.

All in all, my conclusion is that the system used to write JavaScript for client validation in MVC 2 is completely hard-wired to that task and not extensible for other purposes.


  • Guest
    Mason Wheeler Thursday, 9 September 2010

    So in other words, not only does Microsoft not know how to write code in general--a well-known fact among those who have ever had to work with their products--they also don't know how to write code that writes other code.

    For some reason, this does not come as a big surprise to me.

  • Guest
    Ravi Sunday, 15 January 2012

    I wasted a ton of time figuring this out. Thanks.

  • Please login first in order for you to submit comments
  • Page :
  • 1

Check out more tips and tricks in this development video: