How Does Html.EnableClientValidation() Inject JavaScript?
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
The
Therefore, client-side validation will not work if you manually write a
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
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.
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:- Writes a
</form>
closing tag. No surprise there. - 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.

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.