Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Multiple Interfaces with MVC DataAnnotations and MetaDataType
    text
    copied!<p>I am applying validation using DataAnnotations to an MVC ViewModel which is a composite of several entity framework objects and some custom logic. The validation is already defined for the entity objects in interfaces, but how can I apply this validation to the ViewModel?</p> <p>My initial idea was to combine the interfaces into one and apply the combined interface to the ViewModel, but this didn't work. Here's some sample code demonstrating what I mean:</p> <pre class="lang-cs prettyprint-override"><code>// interfaces containing DataAnnotations implemented by entity framework classes public interface IPerson { [Required] [Display(Name = "First Name")] string FirstName { get; set; } [Required] [Display(Name = "Last Name")] string LastName { get; set; } [Required] int Age { get; set; } } public interface IAddress { [Required] [Display(Name = "Street")] string Street1 { get; set; } [Display(Name = "")] string Street2 { get; set; } [Required] string City { get; set; } [Required] string State { get; set; } [Required] string Country { get; set; } } // partial entity framework classes to specify interfaces public partial class Person : IPerson {} public partial class Address : IAddress {} // combined interface public interface IPersonViewModel : IPerson, IAddress {} // ViewModel flattening a Person with Address for use in View [MetadataType(typeof(IPersonViewModel))] // &lt;--- This does not work. public class PersonViewModel : IPersonViewModel { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public string Street1 { get; set; } public string Street2 { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } } </code></pre> <p>My real-world problem involves about 150 properties on the ViewModel, so it's not as trivial as the sample and retyping all the properties seems like a horrible violation of DRY.</p> <p>Any ideas on how to accomplish this?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload