Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Accessing ModelMetadata for items in a collection

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?

like image 646
devuxer Avatar asked Mar 14 '10 03:03

devuxer


1 Answers

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) %>
like image 66
Darin Dimitrov Avatar answered Nov 18 '22 12:11

Darin Dimitrov