If you want to use one of the several validation frameworks for ASP.NET MVC (xVal, Data Annotations attributes, etc) and only validate a subset of a model's fields for a particular action, the easiest solution is to use the [Bind]
attribute.
While I can certainly think of a case where you might only want to validate against a subset of a model's fields (i.e. in a Create
action), I cannot think of a case where you would want the validations for a particular field to be completely different between two different actions.
Here is a simple example, using a Person model object in conjunction with Data Annotations validator attributes. The Create
and Update
action will be validating against a different set of the model's fields.
Model:
public class Person
{
[Required]
Int32 Id { get; set; }
[Required]
String FirstName {get; set;}
[Required]
String LastName {get; set;}
}
Controller Actions:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create( [Bind(Exclude = "Id")] Person person )
{
// this action will not perform any validation checks against the Id property of the model
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Update( Person person )
{
// this action will perform validation checks against all model properties, including Id
}
In the above example, the Create
action will completely ignore the Id
attribute of the Person
model object. It will not attempt to bind this property, nor will it attempt to perform any validations against it. Since a Person would not have an Id at the time of creation, this is exactly what you want. The Update
action, on the other hand, will bind and validate against all properties of the model.
The fact that the Bind
attribute is specified on the method argument can make the code a bit on the ugly side. However, if the Exclude
list gets long, you can always add some additional line breaks and whitespace to help reduce the ugliness.