0

I was wondering if there was a way to pass more than 1 list to a view to render.

Here is my code in PeopleController

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

    //Sites
    List<SelectListItem> listSelectListItem = new List<SelectListItem>();

    foreach (Sites loc in db.Locations)
    {
        SelectListItem selectListItem = new SelectListItem()
        {
            Text = loc.HRSite,
            Value = loc.HRSite
        };
        listSelectListItem.Add(selectListItem);
    }

    SiteViewModel siteViewModel = new SiteViewModel();
    siteViewModel.Sites = listSelectListItem;

    //Cost Centers
    List<SelectListItem> listSelectListItem2 = new List<SelectListItem>();

    foreach (CostCenter cc in db.CostCenterNumbers)
    {
        SelectListItem selectListItem = new SelectListItem()
        {
             Text = cc.CostCenterNumber,
             Value = cc.CostCenterNumber
        };
        listSelectListItem2.Add(selectListItem);
    }

    CCViewModel ccViewModel = new CCViewModel();
    ccViewModel.CostCenter = listSelectListItem2;

    List<object> myModel = new List<object>();
    myModel.Add(siteViewModel);
    myModel.Add(ccViewModel);

    return View(myModel);

Here is my View:

@model IEnumerable<object>
@{
    List<MVCDemo.Models.CostCenter> lstCostCenter = Model.ToList()[0] as List<MVCDemo.Models.CostCenter>;
    List<MVCDemo.Models.Sites> lstLocation = Model.ToList()[1] as List<MVCDemo.Models.Sites>;

}

<h3>Cost Center</h3>
<ul>
    @foreach (var item in lstCostCenter)
    {
        <li>@item.CostCenterNumber</li>
    }
</ul>
<hr />
<h3>Site</h3>
<ul>
    @foreach (var item in lstLocation)
    {
        <li>@item.HRSite</li>
    }
</ul>

How can I change the view to contain 2 listboxes instead of 2 "lists"?

Mikhail Tulubaev
  • 4,141
  • 19
  • 31

2 Answers2

0

Create a concrete view containing a collection for each of your lists.

Then for each of your collections use @Html.ListboxFor(m => m.YourCollection)

More info: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.listboxfor(v=vs.118).aspx

lazarus
  • 371
  • 2
  • 10
0

I suggest creating a ViewModel to hold your data. It is far more convenient that simply passing "object" around. There are many benefits of it and one would be that you could use the strongly typed html helpers in razor. Then you can use the @Html.ListboxFor as suggested by dan m

Community
  • 1
  • 1
Judge Bread
  • 501
  • 1
  • 4
  • 13