MVC4 ViewBag or ViewModel or?

I need to send the data as a list for two different models in my database for presentation in an MVC4 project.

Something like that:

controller

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

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

    return View();
}

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>

The view displays two lists, one list for each model.

I'm not sure what is the most efficient way to do this?

ViewModel?

ViewData / Viewbag?

Something else?

(Please, no third-party suggestions)

UPDATE

Next, I have been trying for more than an hour to implement an answer that offers List<T>Viewmodel without any luck. I believe this is because my Viewmodel looks like this:

public class GalleryViewModel
{
    public Cat cat { get; set; }
    public Dog dog { get; set; }
}
+5
source share
1 answer

Try to explain your problem and your goal, so we know (specifically) what you are trying to do.

, , . - , , , , , .

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; }
}

Model

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()
}

(, # )

+7

All Articles