这可能是个人喜好问题,但在创建 ViewModel 时,最好使用如下所示的多个公共类(请记住,这 3 个类仅服务于一个视图):
namespace WebApp.Areas.Commerce.Models.ViewModels
{
public class TravellersViewModel
{
public TicketHolder TicketHolder { get; set; }
public List<Traveller> TicketMembers { get; set; }
public int MaxAge { get; set; }
public bool ShowAddress { get; set; }
}
public class TicketHolder
{
public string EmailAddress { get; set; }
public string TelephoneNumber { get; set; }
public string MobileNumber { get; set; }
public string Address1 { get; set; }
public string Postcode { get; set; }
public string Country { get; set; }
}
public class Traveller
{
public int Id { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
public bool Policyholder { get; set; }
public Traveller()
{
Title = "Mr";
}
}
}
还是最好将子类嵌套在单视图模型的范围内
namespace WebApp.Areas.Commerce.Models.ViewModels
{
public class TravellersViewModel
{
public TicketHolderDetails TicketHolder { get; set; }
public List<Traveller> TicketMembers { get; set; }
public int MaxAge { get; set; }
public bool ShowAddress { get; set; }
public class TicketHolderDetails
{
public string EmailAddress { get; set; }
public string TelephoneNumber { get; set; }
public string MobileNumber { get; set; }
public string Address1 { get; set; }
public string Postcode { get; set; }
public string Country { get; set; }
}
public class Traveller
{
public int Id { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
public bool Policyholder { get; set; }
public Traveller()
{
Title = "Mr";
}
}
}
}
我非常喜欢构建视图模型的第二种方式,因为它可以将所有内容保持在一起。