MVC在不同情况下的必需验证属性

时间:2014-04-16 12:54:37

标签: c# asp.net-mvc class requiredfieldvalidator

假设我们有一个类 Client

  public class Client
  {
    public int ID { get; set; }
    public int Type { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string County { get; set; }
    public string Town { get; set; }
    public string PostalCode { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }

    public string StudentName { get; set; }
    public string Birthdate { get; set; }

    public string Company { get; set; }

    public string Observations { get; set; }
   }

客户的类型(字段 Type )可以是1(人)或2(公司)。

如何为这两种情况添加不同的必需属性?

我希望第一个案例(人)具有以下字段的必需属性:ID,TYPE,名称,地址和电子邮件。

对于第二种情况(公司),我想添加以下所需的属性:ID,TYPE, StudentName ,地址,公司和电子邮件。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

有一个名为" MVC Foolproof Validation"为了这: http://foolproof.codeplex.com/

答案 1 :(得分:0)

这可能是这样的:

class Client
{
    [Required]
    public int ID { get; set; }
    [Required]
    public string Address { get; set; }
    [Required]
    public string Email { get; set; }
    public string Country { get; set; }
    public string Town { get; set; }
    public string PostalCode { get; set; }
    public string Phone { get; set; }
    public string Birthdate { get; set; }
    public string Observations { get; set; }
}

class Person : Client
{
    [Required]
    public string Name { get; set; }
}

class Company : Client
{
    [Required]
    public string StudentName { get; set; }
    [Required]
    public string Company { get; set; }

}

顺便问一下你自己:"我想要的人","我想要公司" - 这表明你想要2个不同的类,而不是一个。