Asp.net MVC 2.0 Data Annotations Validation doesn’t emit correct JSON
Apparently I’m not the only one to have this sneaky little problem that has been driving me mad. Given the simple model:
public class Foo {
[Required] public string Bar {get;set;}
}
And a simple view:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<Foo>" %>
<%@ Import Namespace="MvcApplication2.Models"%>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcJQueryValidation.js" type="text/javascript"></script>
<h2>Index</h2>
<%= Html.ValidationSummary() %>
<% Html.EnableClientValidation(); %>
<%
using (Html.BeginForm())
{
ViewContext.FormContext.ClientValidationFunction = "EnableClientValidation"; %>
<%= Html.LabelFor(x=>x.Bar) %>
<%= Html.TextBoxFor(x=>x.Bar) %>
<input type="submit" />
<% } %>
</asp:Content>
You would expect the form to emit the JSON needed to pass to the jQuery validator right? WRONG! It just outputs the following
<script type="text/javascript">
//<![CDATA[
EnableClientValidation({"Fields":[],"FormId":"form0"}, null);
//]]>
</script>
That’s no help; however, when you give it the <%= Html.ValidationMessageFor(x=>x.Bar) %> you start to see what you expect.
Comments(1)
Thanks to a StackOverflow user, I’ve also been enlightened you can do Html.ValidateFor if you don’t have a need for the message.