views:

10

answers:

1

Hi, how can I apply Required Attribute like validation to the following without knowing how many elements will be in each collection:

public class MyViewPageViewModel
{
  [Required]
  public List<int> IntCollection { get; set; }

  [Required]
  public Dictionary<int, string> IntAndStringAllValueCollection { get; set; }

  [Required("Value")]
  public Dictionary<int, string> IntAndStringValueValidationCollection { get; set; }

  [Required("Name","HairColor")]
  public List<Person> PersonNameValidationCollection { get; set; }

}

For IntCollection I want every element to be required. For IntAndStringAllValueCollection I want every Key and every Value to be required. For IntAndStringValueValidationCollection I do not want the Key to be required but I want the Value to be required.

A: 

Although I'd like to be able to do it as expressed above, one way to get around the problem is like so:

public class PageViewModel
{
    public List<RequiredStartAndEndDateTuple> OnlineDates { get; set; }
}

public class RequiredStartAndEndDateTuple
{
    public RequiredStartAndEndDateTuple() { }
    public RequiredStartAndEndDateTuple(DateTime? startDate, DateTime? endDate)
    {
        OnlineStartDate = startDate;
        OnlineEndDate = endDate;
    }

    [Required(ErrorMessage = "Start Date Required")]
    public DateTime? OnlineStartDate { get; set; }

    //-- Note, no attribute means end date not required
    public DateTime? OnlineEndDate { get; set; }
}

And if you're interested in the Controller & View Bits, check out:

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Specifically grab the project source code and check out the 'Sequential' page using the strongly typed helpers

Jonathon Kresner