0

各コレクションに含まれる要素の数を知らなくても、検証のような必須属性を次のように適用するにはどうすればよいですか。

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; }

}

IntCollection の場合、すべての要素を必須にする必要があります。IntAndStringAllValueCollection の場合、すべての Key とすべての Value を必須にする必要があります。IntAndStringValueValidationCollection の場合、キーを必須にする必要はありませんが、値を必須にする必要があります。

4

1 に答える 1

0

上記のようにできるようにしたいのですが、問題を回避する1つの方法は次のとおりです。

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; }
}

Controller & View Bits に興味がある場合は、以下をチェックしてください。

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

具体的には、プロジェクトのソース コードを取得し、厳密に型指定されたヘルパーを使用して「Sequential」ページをチェックしてください。

于 2010-10-22T19:40:58.393 に答える