ASP.NET MVC 5,如何在构成其他视图模型的viewmodel上启用验证注释?

时间:2015-03-17 20:48:13

标签: c# asp.net asp.net-mvc asp.net-mvc-5 viewmodel

我正在构建的社交网络应用程序中有一个非常复杂的用户配置文件系统。配置文件页面包含用于区分每种用户配置文件信息的选项卡:基本,教育,作业。 UserProfileViewModel位于所有内容之上,由内部视图模型组成,如BasicViewModel,EducationViewModel和JobViewModel。考虑如下结构:

    public class ProfileViewModel
{
    public string id { get; set; }
    public BasicViewModel basic { get; set; }
    public EducationViewModel education { get; set; }
    public JobViewModel job { get; set; }
}

public class BasicViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime? DateOfRegistration { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public string Gender { get; set; }
    public string PhoneNumber { get; set; }
    [Display(Name = "Biography")]
    public string Biography { get; set; }
    public string NickName { get; set; }
    public string FavoriteQuotes { get; set; }
}

public class EducationViewModel{
    public string EducationStatus { get; set; }
    public List<University> Universities { get; set; }
    public string CourseStatus { get; set; }
    public string CourseSpecialization { get; set; }
    public List<string> EducationEvents { get; set; }
}

public class JobViewModel
{
    public string WorkStatus { get; set; }
    public List<Company> Companies { get; set; }
}

public abstract class Organization
{
    public string Name { get; set; }
    public DateTime? Year { get; set; }
    public int TimePeiod { get; set; }
}

public class University: Organization
{
    public string Degree { get; set; }
    public string Profession { get; set; }
}

public class Company: Organization
{
    public string Website { get; set; }
    public string Position { get; set; }
}

所以问题是,模型验证的数据注释(服务器端和客户端端)是否适用于具有这种复合结构的模型?如果是这样,我是否只是像通常用简单视图模型那样放置注释?如果没有,我怎样才能以其他方式实现这一目标?请帮忙。

1 个答案:

答案 0 :(得分:0)

任何单个视图模型都可能包含其他视图模型:

此模型是服务器端:

[Serializable]
public class MyBigViewModel : IValidatableObject 
    {
       public MyBigViewModel(){
          MyOtherViewModel = new MyOtherViewModel();
          MyThirdViewModel = new MyThirdViewModel();
      }
      public MyOtherViewModel {get;set;}
      public MyThiddViewModel {get;set;} 

    public void Post(){
           //you can do something here based on post back 
           //like maybe this where the post method here processes new data
           MyOtherViewModel.Post();

    }

}

控制器可能如下所示:

  public ActionResult UserList (MyBigViewModel uvm){
      if(ModelState.IsValid){
         uvm.Post();
         return View(uvm);

      }
    return View(uvm);
  }

你可以实现IValidateableObject来做服务器端&#34;验证。但是,在上面的示例中,我们希望每个viewmodel都包含&#34;包含&#34;它是自己的验证模型。

每个viewmodel属性都可以使用数据注释&#34;包含&#34;仅在该视图模型中。这是一个非常好的方式来遏制&#34;包含&#34;你想要什么,你想要什么。

我经常在主VM中使用多个Viewmodel,并根据需要使用部分视图传递它们。