views:

67

answers:

1

I'm trying to write an auto-scaffolder for Index views. I'd like to be able to pass in a collection of models or view-models (e.g., IEnumerable<MyViewModel>) and get back an HTML table that uses the DisplayName attribute for the headings (th elements) and Html.Display(propertyName) for the cells (td elements). Each row should correspond to one item in the collection.

When I'm only displaying a single record, as in a Details view, I use ViewData.ModelMetadata.Properties to obtain the list of properties for a given model. But what happens when the model I pass to the view is a collection of model or view-model objects and not a model or view-model itself?

How do I obtain the ModelMetadata for a particular item in a collection?

+1  A: 

A simple extension method might do the job:

public static class MyExtensions
{
    public static ModelMetadata GetMetadata<TModel>(this TModel model)
    {
        return ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TModel));
    }
}

And in your view:

<%@ Page 
    Language="C#"
    Inherits="System.Web.Mvc.ViewPage<System.Collections.Generic.IEnumerable<MyViewModel>>" %>

<%-- Get metadata for the first item in the model collection --%>
<%= Html.Encode(Model.ElementAt(0).GetMetadata().ModelType) %>
Darin Dimitrov
That's what I needed, thanks!
DanM