1

I something similar to the following

class EntityNameId
{
    public string Name { get; set; }
    public string Id { get; set; }
}

class OrganizationNameId : EntityNameId
{
}

class PersonViewModel
{
    public PersonViewModel()
    {
        Organization = new OrganizationNameId();
    }
    OrganizationNameId Organization { get; }
}

How can I set the Required attribute in PersonViewModel for OrganizationNameId.Id so that client-side validation will work? I don't want to put it in OrganizationNameId or EntityNameId because its not always required, but it is required for PersonViewModel. I am using MVC 3.

Edit: I do not want to add a custom property as described below by Bas. I have a custom partial view for EntityNameId that allows for it to be reusable.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • check this this out , i already answered this question here http://stackoverflow.com/a/24757520/3050647 – elia07 Jul 15 '14 at 12:14

2 Answers2

0

One option is to add a property to PersonViewModel that binds to the organisation property:

[Required]
public int OrganizationId {
   get { return Organization.Id; }
   set { Organization.Id = value }
}
Bas
  • 26,772
  • 8
  • 53
  • 86
0
public class EntityNameId
{
    public string Name { get; set; }
    public string Id { get; set; }
}

[MetadataType(typeof(OrganizationNameIdMetadataType))]
public class OrganizationNameId : EntityNameId
{
}

public class PersonViewModel
{
    public PersonViewModel()
    {
        Organization = new OrganizationNameId();
    }
    public OrganizationNameId Organization { get; private set; }
}

public class OrganizationNameIdMetadataType
{
    [Required]
    public object Id { get; set; }
}

Customizing ASP.NET MVC 2 - Metadata and Validation

How about use MetadataType attribute?

takepara
  • 10,413
  • 3
  • 34
  • 31