简体   繁体   中英

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 (eg, 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?

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) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM