views:

714

answers:

2

I am trying to trace through why my ASP.NET MVC 2 validation isn't working, but I cant find enough about HOW it works to be able to do this.

I have followed the steps in this useful article by David Hayden which seems to be the best documentation currently out there, but nothing actually happens.

I get validation when i submit to the server (as I did since Preview 1 when i added data annotations to my model) but I'm not getting any client side validation.

How can i trace through to test? So far I have verified the following obvious things

  • MicrosoftMvcJQueryValidation.js and jquery.validate.min.js files are being downloaded
  • Html.ClientValidationEnabled = true

I cant see easily what is hooking up to which events to know quite how to debug it.

+1  A: 

In order for a field to be validated client-side you have to specify a call to Html.ValidationMessage/Html.ValidationMessageFor<> for the field (just like David did in the tutorial you linked) within the view. This is essentially a trigger to the client-side validation logic that you want to run validation for that field.

If there are situations where you don't actually want a validation message to visually appear for each field (i.e. by using Html.ValidationMessage), but would rather allow a summary to be the sole source of validation error messages (i.e. by using Html.ValidationSummary), you still need some way to "trigger" the validation to occur for the specific fields you want it to. This can be achieved by using the Html.Validate/Html.ValidateFor<> methods within your view. Those helpers won't render anything, but will simply register the specified field for client-side validation.

Both of those requirements exist since you might not want the client-side validation to automatically validate every property on your model object, since some of them might not even be part of the form that you're wanting validated.

LostInTangent
+2  A: 

Here's what I've learnt:

MOST IMPORTANT

  • Your HTML Form must be created with the using directive, not just BeginForm and EndForm.
  • You must set Html.ClientValidationEnabled = true BEFORE you start your 'Form'
  • You must use Html.ValidationMessage for each field
  • You must set Html.ClientValidationEnabled = true on each partial control (ascx)

HOW IT WORKS (very simple overview)

  • When you do Html.BeginForm it creates a 'FormContext' in the ViewContext
  • When ValidationMessage helpers are used, metadata is put into the form context
  • When the form is disposed (by the using statement) it writes out all the validation code

MISC

  • I cannot seem to get validation working when I have a partial control, if that control uses a different model from the view that defines the Form.

  • You do NOT need to use Html.TextBoxFor or Html.ValidationMessageFor, you can use Html.TextBox and Html.ValidationMessage

Simon_Weaver