views:

87

answers:

2

I would like to display a tag cloud in my test application using a helper class to create the html.

I can use a for each loop in the partial view to visit each item in the model

Inherits="System.Web.Mvc.ViewUserControl < IEnumerable < MyTestproject.Models.TagCount > >

foreach (var item in Model) {

}

But when I try to pass the model to the Helper class and use a for each loop I receive the following error:

public static string DisplayCloud < TagCount >(TagCount objTags) {

..
       foreach (var item in objTags) {

       }
}

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

What is the difference or am I passing it incorrectly?

+1  A: 

Because you're passing a different type.

The view is getting IEnumerable<TagCount>

The helper is getting TagCount

Your helper code needs to be:

public static string DisplayCloud(IEnumerable<TagCount> objTags) {

..
       foreach (var item in objTags) {

       }
}

The generic type on the method seems useless/illegal, since it's an actual type, so I removed it, as well as fixing the argument type.

Craig Stuntz
Made the change, ran the code and of course it works a treat. Cheers!
Nicholas Murray
Be sure to upvote answers that helped you. :)
Nathan Taylor
+1  A: 

Look more closely at the difference between your view's class signature and your helper method's signature:

Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<MyTestproject.Models.TagCount>>

public static string DisplayCloud<TagCount>(TagCount objTags)

The method needs to receive an IEnumerable<TagCount> in order to call foreach.

Nathan Taylor
Thanks, but how do I pass it correctly I am currently using the following: <%= TagCloudHelper.DisplayCloud(Model) %>
Nicholas Murray
You are passing it correctly assuming Model is an IEnumerable<TagCount>, however your method signature needs to be modified to accept that parameter.
Nathan Taylor
Unfortunately I not sure how to do that, do you mean something like this?: public static string DisplayCloud IEnumerable<TagCount>(TagCount objTags)
Nicholas Murray
Craig corrected me above. (was nearly there?!?) Thanks.
Nicholas Murray