views:

24

answers:

1

In his blog post, Scott Guthrie describes how to enable validation using DataAnnotations.

Example:

public class Product
{
    [Display(Name="Product Number")]
    [Range(0, 5000)]
    public int ProductID { get; set; }

    [Display(Name="Name")]
    [Required]
    public string ProductName { get; set; }

    [Display(Name="Price")]
    [DataType(DataType.Currency)]
    public double ListPrice { get; set; }
}

In the comments to this blog post @Ke wrote:

How do the server side validations work with ajax post? i.e, how can i send the validation errors back to the client?

Scott replied with:

Yes - you can handle this. I believe Phil Haack has it on his list to blog about soon.

I cannot find this blog post though. How do I combine server-side validation with an AJAX post?

The best options I've seen seem to involve using partials to send the form back to the client. I would rather use client-side Javascript to enable the error messages.

A: 

The way data annotation validation works is by applying special css classes to the fields containing errors and error messages are shown by html helpers that generate the corresponding divs. So indeed the best option would be to return a partial view containing the form allowing you to show the error messages.

If you want to use JSON or XML instead you will have to pass the validation errors manually in the response structure and handle it manually using javascript in the success callback.

As far as client-side validation is concerned, it will work because the form won't be submitted (using ajax or not) if validation fails.

Darin Dimitrov