开发者

Cannot apply foreach?

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 Ca开发者_如何转开发rreraController and creating a linq query that returns all the names and saving it to a simple List<string>.

How can I achieve this?

ViewData["Areas"] = area.FindAllAreas().Select(????


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"])


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜