views:

441

answers:

1

I'm trying to get setup using the DataAnnotations validator in ASP.Net MVC 2.0 Beta, but with the following model:

public class Foo {
    [Required] public string Bar {get;set;} 
}

And the following code in my view:

 <%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<Foo>" %>

 <!-- later on -->
 <% Html.EnableClientValidation(); %>
 <% using (Html.BeginForm("Edit","Foo")) { %>

Everything is almost verbatim form the examples. What is emitted is:

<script type="text/javascript">
//<![CDATA[
EnableClientValidation({"Fields":[],"FormId":"form0"}, null);
//]]>
</script>

Nothing is ever emitted to tell whatever JavaScript validation library (jQuery or MS Ajax, doesn't matter) to validate the fields. The validation does happen on the server side, but never on the client, for obvious reasons.

A: 

The answer is a bit sneaky. I found out the problem is the lack of ValidationMessageFor even though there is a ValidationSummary. After adding the following:

<%=Html.ValidationMessageFor(x=>x.Bar)%>

The proper JSON was emitted and the jQuery validation worked.

It seems odd you have to have the message even though you have the validation summary.

Mark
Use Html.Validate() or Html.ValidateFor() if you want validation but don't want a message span.
Levi
@Levi Thanks! I'll give that a shot.
Mark