Problems passing a list from ASP.NET MVC controller to a view

23 Views Asked by At

I'm experiencing a problem passing a list from a controller to a view. Doing it this way works fine but I don't want to be passing the entire table.

What I want to do is pass just the results of the studies query:

ViewBag.studyList = new SelectList(_context.Studies.OrderBy(p => p.Name), "Id", "Name");

but if I put studies instead of _context.Studies like this:

var studies = (from t in _context.Studies
               where !((from s in _context.Studies
               join sn in _context.StudyNodes on s.Id equals sn.StudyId
               where sn.NodeId == id
               select s.Id).ToList()).Contains(t.Id)
               select new BundleNodeViewModel
               {
                   StudyId = t.Id,
                   StudyName = t.Name
               }).ToList();

ViewBag.studyList = new SelectList(studies.OrderBy(p => p.StudyName), "Id", "Name");

The code throws a null exception error in the view.

How can this be a problem? I need to pass the filtered results as per the studies query and not the entire list which is the only way it seems to work.

Can someone help please so I can pass studies and not _context.Studies.

Thanks for your help.

1

There are 1 best solutions below

0
Yat Fei Leong On

So your result from studies is list of BundleNodeViewMode and you want to list the item from there. Then you should tell the selectlist what is the Id and Name you are displaying from.

ViewBag.studyList = new SelectList((from s  in studies.OrderBy(p => p.StudyName), select new {Id = s.StudyId, Name = s.StudyName}) , "Id", "Name");