I have a form displaying fields from 2 tables in database. I want to validate this form using Data Annotation model validation technique in MVC4. I am confused whether Data Annotation validation attributes should be applied to individual models(tables) or should I create separate model consisting of fields from both tables.
2 Answers
You should create a new model containing the information you want to display on your view. This specific model has a name: it's called view model. You should always pass view models to your views from the controller actions and your controller actions should always take view models as parameters. Then you could decorate the properties on this view model with validation attributes.

- 1,023,142
- 271
- 3,287
- 2,928
-
Thanks for your reply. Is there any other way of accomplishing this, like -- I would assign data annotation attributes to individual models(tables)only once and I don't have to assign data annotation attributes again to new view model. – Chinu Dec 31 '12 at 12:19
You can do both things. You can decorate your domain model classes and view models. Both things are correct. The thing is that for your view, it's better to use a view model instead of model classes. No need to expose the whole domain model in you view
Just add using System.ComponentModel.DataAnnotations;
namespace and add the attributes you need on each property.
For example:
public class BankAccount
{
[Required]
public Person Person { get; set; }
[Required]
public AccountType AccountType { get; set; }
[Required, StringLength(256)]
public string BankName { get; set; }
}

- 3,552
- 1
- 17
- 21