2013-05-01 68 views
5

我需要将数据库中两个不同模型的列表形式的数据发送到MVC4项目中的视图。MVC4 ViewBag或ViewModel或?

事情是这样的:

控制器

public ActionResult Index() 
{ 
    Entities db = new Entities(); 

    ViewData["Cats"] = db.Cats.toList(); 
    ViewData["Dogs"] = db.Dogs.toList(); 

    return View(); 
} 

查看

@* LIST ONE *@ 
<table> 
    <tr> 
     <th> 
      @Html.DisplayNameFor(model => model.ListOneColOne) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.ListOneColTwo) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.ListOneColThree) 
     </th> 
    </tr> 

@foreach (var item in @ViewData["Cats"]) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.ListOneColOne) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.ListOneColTwo) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.ListOneColThree) 
     </td> 
    </tr> 


@* LIST TWO *@ 
<table> 
    <tr> 
     <th> 
      @Html.DisplayNameFor(model => model.ListTwoColOne) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.ListTwoColTwo) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.ListTwoColThree) 
     </th> 
    </tr> 

@foreach (var item in @ViewData["Dogs"]) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.ListTwoColOne) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.ListTwoColTwo) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.ListTwoColThree) 
     </td> 
    </tr> 

观是显示两个列表的,一个列表每个型号。

我不确定最有效的方法是什么?

Viewmodel?

Viewdata/Viewbag?

还有其他的东西吗?

(请没有第三方的建议)

UPDATE

而且我已经尝试了一个多小时,现在实行的答案提示有List<T>视图模型没有任何的运气。我相信这是由于这样的事实,我的视图模型看起来像这样:

public class GalleryViewModel 
{ 
    public Cat cat { get; set; } 
    public Dog dog { get; set; } 
} 

回答

7

试图解释你的问题,你的目标,所以我们知道(特别是)你想要做什么。

我认为这意味着你有两个列表,你想发送它们到一个视图。做到这一点的一种方法是将两个列表放入模型并将模型发送到视图,但您似乎已经指定您已经有两个模型,所以我会按照这个假设去做。

控制器

public ActionResult Index() 
{ 
    ModelA myModelA = new ModelA(); 
    ModelB myModelB = new ModelB(); 

    IndexViewModel viewModel = new IndexViewModel(); 

    viewModel.myModelA = myModelA; 
    viewModel.myModelB = myModelB; 

    return View(viewModel); 
} 

视图模型

public class IndexViewModel 
{ 
    public ModelA myModelA { get; set; } 
    public ModelB myModelB { get; set; } 
} 

型号

public class ModelA 
{ 
    public List<String> ListA { get; set; } 
} 

public class ModelB 
{ 
    public List<String> ListB { get; set; } 
} 

查看

@model IndexViewModel 

@foreach (String item in model.myModelA) 
{ 
    @item.ToString() 
} 

(很抱歉,如果我的C#是生锈)

+0

感谢@row我一直试图让这个工作,但我似乎无法弄清楚。显然问题是我的ViewModel不是由'List '组成的,而是实际的模型类型,例如'public ListA listA {get;组; }'。我要更新我的初始文章以反映这一点。 – 2013-05-01 07:01:23

+0

花了一段时间,但我明白了!谢谢罗文。 – 2013-05-01 08:13:29

相关问题