Custom html helper with LINQ expression in MVC 3

I am creating a custom HTML helper with an expression to draw a tag cloud where the data that falls into the tag cloud comes from the expression. I will let the code say here:

Show model

public class ViewModel { public IList<MyType> MyTypes { get; set; } public IList<MyOtherType> MyOtherTypes { get; set; } } 

View

 <div> @Html.TagCloudFor(m => m.MyTypes) </div> <div> @Html.TagCloudFor(m => m.MyOtherTypes) </div> 

Assistant

 public static MvcHtmlString TagCloudFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) where TProperty : IList<MyType> where TProperty : IList<MyOtherType> { // So my actual question here is: how do I get my IList<TProperty> collection // so I can iterate through and build my HTML control } 

I quickly looked around and did the usual Google searches, but I can’t find such an answer. I assume it is somewhere in the scope of expression.Compile().Invoke() , but I'm not sure if the correct parameters should pass.

I should also note that MyType and MyOtherType have a similar Id property, but there is no inheritance, they are completely separate objects, so I hold back my TProperty as IList<MyType> and IList<MyOtherType> . I am going the wrong way here, I feel how it should be obvious, but my brain is not playing.

+4
source share
2 answers

The following should do it:

 public static MvcHtmlString TagCloudFor<TModel , TProperty>( this HtmlHelper<TModel> helper , Expression<Func<TModel , TProperty>> expression ) where TProperty : IList<MyType>, IList<MyOtherType> { //grab model from view TModel model = (TModel)helper.ViewContext.ViewData.ModelMetadata.Model; //invoke model property via expression TProperty collection = expression.Compile().Invoke(model); //iterate through collection after casting as IEnumerable to remove ambiguousity foreach( var item in (System.Collections.IEnumerable)collection ) { //do whatever you want } } 
+8
source

What about....

 public static MvcHtmlString TagCloudFor<TModel , TItemType>( this HtmlHelper<TModel> helper , Expression<Func<TModel , IEnumerable<TItemType>>> expression ) // optional --- Where TItemType : MyCommonInterface { TModel model = (TModel)helper.ViewContext.ViewData.ModelMetadata.Model; //invoke model property via expression IEnumerable<TItemType> collection = expression.Compile().Invoke(model); foreach( var item in collection ) { //do whatever you want } } 
+1
source

All Articles