C# 重用视图模型和数据注释

C# 重用视图模型和数据注释,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我对ASP MVC非常陌生,所以当我第一次创建页面时,我创建了一个ViewModel,它具有与地址和联系人信息相关的扁平属性。这些属性非常常见,我可以看到它们被重用。假设我有下面的视图模型: public class InformationViewModel { [Required(ErrorMessage = "Name is required")] public string Name { get; set; } public string Phone { get;

我对ASP MVC非常陌生,所以当我第一次创建页面时,我创建了一个ViewModel,它具有与地址和联系人信息相关的扁平属性。这些属性非常常见,我可以看到它们被重用。假设我有下面的视图模型:

public class InformationViewModel {
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }
    public string Phone { get; set; }
    public string EMail { get; set; }
    public Uri WebSiteURL { get; set; }
    public Uri FacebookURL { get; set; }

    [HiddenInput(DisplayValue = false)]
    public string AddressId { get; set; }
    public string AttentionLine { get; set; }
    public string CareOf { get; set; }
    public string CountryCode { get; set; }
    public string CountryName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public Dictionary<string, string> Countries { get; set; }
    public Dictionary<string, string> States { get; set; }
    public string StateCode { get; set; }
    public string StateName { get; set; }
    public string PostalCode { get; set; }

    //Some other properties specific to the view here
}
公共类信息视图模型{
[必需(ErrorMessage=“Name is Required”)]
公共字符串名称{get;set;}
公用字符串电话{get;set;}
公共字符串电子邮件{get;set;}
公共Uri网站URL{get;set;}
公共Uri FacebookURL{get;set;}
[HiddenInput(DisplayValue=false)]
公共字符串地址ID{get;set;}
公共字符串注意线{get;set;}
{get;set;}的公共字符串
公共字符串CountryCode{get;set;}
公共字符串CountryName{get;set;}
公共字符串地址1{get;set;}
公共字符串地址2{get;set;}
公共字符串City{get;set;}
公共字典国家{get;set;}
公共字典状态{get;set;}
公共字符串状态码{get;set;}
公共字符串StateName{get;set;}
公共字符串PostalCode{get;set;}
//此处视图特定的一些其他属性
}
前两个属性块可跨多个视图模型重用。现在,我正在开发一个需要这些相同属性的新页面

1) 我是否会将它们分离到它们自己的视图模型(或模型?)文件中(例如AddressViewModel/ContactViewModel)

1a)如果我将它们分离出来,并通过将它们作为属性包含在
InformationViewModel
中来重用它们,那么这是否会与以下行一起:
public AddressViewModel AddressViewModel{get;set;}


2) 如何删除或应用包含的视图模型中的数据注释(例如,
public AddressViewModel AddressViewModel{get;set;}
?例如,如果我希望某些视图需要名称,而其他视图则不需要名称。

视图模型特定于视图。因此,创建视图特定的平面视图模型是一个好主意。但是如果在多个视图模型中有一些公共属性,则可以根据需要从基本视图模型继承

public class CreateUser
{
  [Required]
  public string Name {set;get;}
  [Required]
  public string Email {set;get;}

  public virtual string City { set; get; }
}
public class CreateUserWithAddress : CreateUser
{
  [Required]
  public string AddressLine1 {set;get;}
  public string AddressLine12 {set;get;}

  [Required]
  public override string City { set; get; }  // make city required
}

从基本视图模型导入时,您应该能够重写基类的属性,并向子类中的属性添加数据注释(就像我们对
City
property所做的那样)。但无法删除派生类中基类中定义的数据批注。

如果改用接口,则VM可以实现许多“基”类型,例如
CreateUserWithAddress:ICreateUser,ICreateAddress