Question

I have 2 classes containg POCO entities in MVC3

public class TeamMember 
{
  public DateTime JoinDate { get; set; }
  [Required]
  Public string Name{ get; set; }
} 

public class Project
{
   [Required]
   public string Name { get; set; }  
   public DateTime StartDate { get; set; }
}

I want to set the default value of TeamMember JoinDate with Project StartDate. Can anybody pull me out of this

Was it helpful?

Solution

You could do it in the controller, something like:

if(teamMember.JoinDate == null)
{
    teamMember.JoinDate = project.StartDate;
}

and you could add more logic if project.StartDate == null then project.StartDate = DateTime.Now.

I'm not sure you can do this as a default in the model itself though.

Update

As you have it, I don't think the Project StartDate can see the TeamMember JoinDate, I think you will need to give them a one to one relationship. I'm not sure of the exact syntax since I'm not on my work system, but something like this should work:

    public class TeamMember 
    {
      public DateTime JoinDate
      { 
          get { return this.JoinDate; }
          set { JoinDate = this.Project.StartDate; }
      }
      [Required]
      public string Name{ get; set; }
      public virtual Project Project { get; set; }
    } 

    public class Project
    {
       [Required]
       public string Name { get; set; }  
       public DateTime StartDate { get; set; }
    }

Update 2

Thinking about it, you need to allow JoinDate to be null or else it will throw a validation error, then you need to check to see if there is a value for it. Something more like this:

    public class TeamMember 
    {
      public DateTime? JoinDate
      { 
          get { return this.JoinDate; }
          set
          {
              if(JoinDate == null)
              {
                  JoinDate = this.Project.StartDate;
              }
              else
              {
                  JoinDate = JoinDate;
              }
          }
      }
      [Required]
      public string Name{ get; set; }
      public virtual Project Project { get; set; }
    }

OTHER TIPS

Sounds like you need a custom model binder for the TeamMember class. This of course assumes that you have access to project.StartDate when TeamMember is being created.

I have used [DefaultValue()] for bool, int, string data type. Try it for DateTime, I am not sure but giving you just workaround.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top