views:

56

answers:

2

I'm trying to get a list of all area in my database:

public ActionResult Index()
        {
            var carreras = repo.FindAllCarreras().ToList();
            AreaRepository area = new AreaRepository();
            ViewData["Areas"] = area.FindAllAreas(); //Return IQueryable<>
            return View("Index", carreras);
        }

And in the View:

<% foreach (var area in ViewData["Areas"])
       { %>

           <p><%: area %></p>

    <% } %>

I get an error:

foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'

I think the best route would be modifying the query in the CarreraController and creating a linq query that returns all the names and saving it to a simple List.

How can I achieve this?

ViewData["Areas"] = area.FindAllAreas().Select(????
+2  A: 

ViewData is a dictionary from string to object. So you are basically doing

object o = ViewData["Areas"];
foreach(var area in o)
...

Just use a cast:

foreach(var area in (WhateverYourCollectionTypeIs)ViewData["Areas"])
Matt Greer
A: 

cast ViewData["Areas"] to (IEnumerable<AREATYPE>)ViewData["Areas"]

Rony
I'm not sure what I should be casting to. Area is a DB table, and using Linq-to-SQL as ORM. What should the IEnumarable type be? :\
Sergio Tapia
@Sergio the same type you get in your `IQueryable<>` from `FindAllAreas`.
Rex M
@Sergio Tapia whatever is returned by `FindAllAreas()` method. Probably something like `Area`.
Necros
That method returns an IQueryable<Area>, but in the View intellisense doesn't 'consider' it and doesn't show its properties or anything.
Sergio Tapia
apply ToList() on FindAllAreas()
Rony