2013-05-01 4 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?

데이터보기/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# 녹슨 경우) 나는이 작업을하지만 난 그것을 알아낼 수없는 것 얻기 위해 노력했습니다 @row

+0

감사합니다. 분명히 문제는 내 ViewModel이 실제 모델 유형이 아닌'List '으로 구성되지 않는다는 것입니다. 예를 들어'public ListA listA {get; 세트; }'. 이를 반영하기 위해 초기 게시물을 업데이트 할 예정입니다. –

+0

잠시 시간을 내었지만 얻었습니다! 로완 고마워. –

관련 문제