2017-08-13 110 views
0

我正在开发一个asp mvc 5网站。我有3种模式,即约会,咨询和联系。现在我想在一个名为userdetails的视图中显示这3个模型的所有细节。我做了什么至今 创建一个视图模型传递多个模型以查看

public class AllServices 
{ 
    public List<Contact> Contacts { get; set; } 
    public List<Appointment> Appointments { get; set; } 
    public List<Consultation> Consultations { get; set; } 
} 

然后创建了控制器的操作方法

public ActionResult userdetails() 
{ 
    AllServices services = new AllServices(); 
    services.Appointments = dbcontext.Appointments.ToList(); 
    services.Consultations = dbcontext.Consultations.ToList(); 
    services.Contacts = dbcontext.Contacts.ToList(); 
    return View(services); 
} 

,并鉴于我做了

@model List<Astrology.ViewModels.AllServices> 
.... 
@foreach(var item in Model) 
{ 
    @item.Appointments 
} 

但是当我运行该页面亚姆得到这样的错误

传入字典的模型项目类型为“Astrology.ViewModels.AllServices”,但此字典需要类型为“System.Collections.Generic.List`1 [Astrology.ViewModels.AllServices]'的模型项目。

有人可以帮我一把。 Iam坚持这一点。

+0

因为你通过AllServices'的'一个实例,其预计AllServices'的'集合的视图。将视图更改为'@model Astrology.ViewModels.AllServices'。并且它的'@foreach(Model.Appointments中的var item){...' –

+0

如果我想通过迭代显示表中所有模型的模型数据。 – Abhijith

+0

阅读第1条评论! –

回答

0

错误是告诉你,当它期望一个AllServices模型列表时,你只传递一个AllServices模型。您需要将视图更改为期望一个模型或将单个模型放入列表中。

编辑(添加的代码示例) 您的控制器更改为这样的事情:

public ActionResult userdetails() 
{ 
    List<AllServices> lservices = new List<AllServices>(); 
    AllServices services = new AllServices(); 
    services.Appointments = dbcontext.Appointments.ToList(); 
    services.Consultations = dbcontext.Consultations.ToList(); 
    services.Contacts = dbcontext.Contacts.ToList(); 
    lservices.Add(services); 
    return View(lservices); 
} 
+0

你能告诉我代码吗?我已经使用该属性的列表声明了视图模型。 – Abhijith

+0

编辑显示代码示例。 –