C# 如何在单个视图中传递两个模型

C# 如何在单个视图中传递两个模型,c#,asp.net-mvc,C#,Asp.net Mvc,我正在使用ASP.NET MVC,我创建了两个模型类,User和Address。我想在同一个视图中使用它们,以允许用户在一个页面上输入所有信息。问题是ASP.NET MVC只允许通过一个模型。解决这种情况的最佳做法是什么 public class Address { [Key] public int Id { get; set; } public int StreetNumber { get; set; } public string Route { get;

我正在使用ASP.NET MVC,我创建了两个模型类,
User
Address
。我想在同一个视图中使用它们,以允许用户在一个页面上输入所有信息。问题是ASP.NET MVC只允许通过一个模型。解决这种情况的最佳做法是什么

public class Address
{
    [Key]
    public int Id { get; set; } 
    public int StreetNumber { get; set; }

    public string Route { get; set;}
    public string City { get; set; }

    public string State { get; set;  }

    public string PostalCode { get; set; }

    public string Coutry { get; set; }

    public int Adresstype { get; set; }
    public int UserId { get; set; }
    public virtual User User { get; set; }
}

public class User
{
    public User()
    {
        this.Ads = new HashSet<Ad>();
        this.Addresses = new HashSet<Address>();
    }

    [Key]
    public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public int PhoneNumber { get; set; }

    public virtual ICollection<Ad> Ads { get; set; }
    public virtual ICollection<Address> Addresses { get; set;}
}
公共类地址
{
[关键]
公共int Id{get;set;}
公共int街道编号{get;set;}
公共字符串路由{get;set;}
公共字符串City{get;set;}
公共字符串状态{get;set;}
公共字符串PostalCode{get;set;}
公共字符串Coutry{get;set;}
公共int地址类型{get;set;}
public int UserId{get;set;}
公共虚拟用户用户{get;set;}
}
公共类用户
{
公共用户()
{
this.Ads=newhashset();
this.Addresses=newhashset();
}
[关键]
公共int Id{get;set;}
公共字符串名{get;set;}
公共字符串LastName{get;set;}
公共字符串电子邮件地址{get;set;}
公共int电话号码{get;set;}
公共虚拟ICollection广告{get;set;}
公共虚拟ICollection地址{get;set;}
}

我们的想法是为这个确切的视图创建一个视图模型,这只是一个类,您可以在其中打包任何您喜欢的东西,比如每个基类中的一个:

public class ViewModel
{
    public User User { get; set; }
    public Address Address { get; set; }
} 
然后将这个视图模型类传递到视图中,您可以轻松地处理用户和地址这两个对象的值