by
30. July 2010 15:59
Soooo.. looks like you're getting the ol'
CS1579: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'
Sucks.
Yeah so I ran into this today. It took a while but eventually found that in the Page directive of my .ASPX page I had a strong type and that type had been since deleted.
<%@ Page ... Inherits="System.Web.Mvc.ViewPage<IEnumerable<SomeClassIDeleted>>" %>
Your code may look different. You may, like me, have SomeClassIDeleted in the Inherets line, or you may simply have "System.Web.MVC.ViewPage". Either way, it's going to piss your application off.
Way down below you will get the CS1579 error becuase the Model variable (and item variable) is simply an instance of object and thus doesn't have all the great properties you creatd and are trying to use.
Between me and a colleague who wants to remain anonymous we came up with a few couple of ways to solve this:
-
The "right" solution:Put the correct type in the IEnumerable type.
Inherits="System.Web.Mvc.ViewPage<IEnumerable<TheRightType>>"
-
The kinda crappy way: Leave the Inherets="System.Web.MVC.ViewPage" alone and cast "Model" and implicitly type "item":
Inherits="System.Web.Mvc.ViewPage"
...
<% foreach (ViewModels.Something item in (List<ViewModels.Something>)Model) {... %>
- The (arguably...) awesome way to do it... with a DYNAMIC! (.NET 4.0+ only)
Inherits="System.Web.Mvc.ViewPage<IEnumerable<dynamic>>"
...
<% foreach (var item in Model) {... %>
Yeah! I love it. This way if you need to change your controller, or the type it returns, as long as the properties are valid it will work with no other code changes. MY COLLEAGUE didn't seem to think this was quite as awesome as I do, as the "item" variable loses it typing and you lose intellisense and all, but I think that is a small price to pay. He says you may as well use Ruby on Rails. Probably right, but hey.
I'm really loving .NET MVC so far, look for more .NET MVC posts in the near future as I get further into this thang.