views:

410

answers:

3

I'm trying to get a very simple client side validation example to work in ASP.NET MVC 2. I'm using data annotations to set a required property "Surname". When I use the Html.ValidationMessageFor(x => x.Surname) the correct client side validation script is written to the page. But when I use Html.ValidationMessage("Surname") the client side validation is not rendered out until after the page has been posted. Client side validation only starts working after a form post! I can see that the script is updated in the page after a form post. There appears to be a bug in Html.ValidationMessage()?

A: 

i've not tried but the metadata are stored on the proprerty so only the ValidationMessageFor has the ability to check the prop (via static reflection).

The other helper use a string key to access a modelstate dictionary without any reference to the property (and no validation metadata info), so i dot't think the Html.ValidationMessage(string key) has the ability to inject validation script client-side.

Andrea Balducci
A: 

As far as I know the validation requires an attempt to validate even if it's client side.

You could try on the GET view creating a new instance of your model, then use TryValidateModel() before sending it to the view. This should cause the validation logic to run and thus to populate the clientside validation, this will result in all required fields showing their error version but depending how you choose to style them this doesn't have to be a big issue.

Chao
+1  A: 

Make sure you are referencing the correct scripts in your master page head.

<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcValidation.js") %>" type="text/javascript"></script>

also look at your view to make sure the client validation call is above your form

<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) {%>
    <%= Html.ValidationSummary(true) %>
    ...
<% } %>

and of course your validation message to show the problem.

<span class="editor-label"><%= Html.ValidationMessageFor(u => u.Name)%></span>

That is really all you need. I believe the required attribute will only start its check if you enter text in the field then remove the text and tab out of the field, so try that to see if you get the validation. Others will validate when the attribute needs to. For example the [StringLength(50)] will show an error message when you exceed 50 characters.

Steve Hook
the question is why ValidationMessage(string key) does not works like ValidationMessageFor() not how to use ValidationMessageFor
Andrea Balducci