ASP.NET MVC: Access ModelMetadata for Items in a Collection

I am trying to write auto-scaffolder to view indexes. I would like to be able to pass a collection of models or view models (e.g. IEnumerable<MyViewModel> ) and return an HTML table that uses the DisplayName attribute for headers ( th elements) and Html.Display(propertyName) for cells ( td elements). Each row must correspond to one element of the collection.

When I show only one entry, as in the Details view, I use ViewData.ModelMetadata.Properties to get a list of properties for this model. But what happens when the model that I pass into the view is a collection of models or objects of the view model, and not the model or view model itself?

How to get ModelMetadata for a specific item in a collection?

+7
asp.net-mvc templates html-helper asp.net-mvc-2 scaffolding
source share
1 answer

A simple extension method can 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 opinion:

 <%@ 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) %> 
+6
source share

All Articles