I recently started using MVC and have been fiddling around with the framework to look at its limitations and one of the things I noticed in the case of validation is the following.
The traditional way to implement validation on MVC would be to implement [Required],[Range] etc at the model level and then use the ModelState.IsValid property at the controller level to make sure the object about to be saved is valid.
But this seems to have a limitation, lets say that I have the following object
[Table(Name = "Products")]
public class Product
{
private int _id;
private string _freeProductId;
[Column(IsPrimaryKey = true, Storage = "_id", Name = "id", IsDbGenerated = true)]
public int Id
{
get
{
return (_id);
}
set
{
_id = value;
}
}
[Required]
[Column(Storage = "_freeProductId", Name = "free_product_id")]
public string FreeProductId
{
get
{
return (_freeProductId);
}
set
{
_freeProductId = value;
}
}
}
I can validate the Product object using ModelState.IsValid at the controller level, to check if the FreeProductId has been entered. But lets say I have a web service that is capable of creating new Products, or any other instance in which I am NOT using the controller to create a new Product object and save it, the [Required] attribute is of no use in such a case and there is no way to check if the object is valid.
I did however dig around a little bit and figured out one way to move all the validation to the object level would be to make all objects implement the IValidatableObject interface and thereby validate all the properties of the object.
Does anyone know another way of doing it ?