3
votes

I'm attempting to write an html helper in which I want to iterate over a known typed property which is a generic list, and output the required HTML content. Here is an outline of how I have constructed the view model to ensure any view models comply with the helper;

Interface definition:

public Interface ITheViewModelInterface<T> where T : class
{
    IEnumerable<T> Items { get; set; }
}

Concrete abstract interface implementation (so that I can define default values) :

public abstract class TheConcreteViewModelImplementation<T> : IViewModelInterface<T> where T : class
{
    public virtual IEnumerable<T> Items { get; set; }
}

ViewModel:

public class TheViewModel : TheConcreteViewModelImplementation<MyListType>
{ 

}

What would be the helper definition such that I could access the correctly typed list of items in the base class? I'm not entirely sure I need a strongly typed helper in this instance, but how do I explicitly pass the items type in the helper call?

1
Have you looked into using Display Templates instead?levelnis
@levelnis, No I haven't looked at display templates in any depth. Do you think this method would be better suited to my requirements?Jez
I think it could be quite a good fit. You would need to create a template with the same name as the type it represents (e.g. MyListType.cshtml) within Views\Shared\DisplayTemplates and then call Html.DisplayFor(m => m.Items) to render your items out.levelnis
Mmm... ok, I'll take a look in more depth. I was rather hoping to access the entire Model though as I need other properties. Would this possible with display templates?Jez
Certainly is - you can use Html.DisplayForModel() and create templates (or use the default ones in the framework) for each data type contained within your model. Have a look at part 4 of Brad's series - it gives a good explanation of customising the default object templatelevelnis

1 Answers

0
votes

After some more research on this matter, I found this discussion which provides some answers (and a rather astounding statement from Microsoft!) to my question;

ASP.NET MVC 3 HtmlHelper Exception does not recognize ModelMetadata on inherited interface