简体   繁体   中英

How to get metadata from IEnumerable<object> in ASP .NET MVC?

I have custom html helper which getting IEnumerable model from view and generates html table with headers and body

please advice how can get matadata from this model

thanks

If I'm understanding what you are trying to do correctly the below should work with minimal reflection:

public static MvcHtmlString MakeTable<TModel, TValue>(this HtmlHelper<TModel> html, IEnumerable<TValue> table)
{
    var modelMetaData = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TValue));

    foreach (TValue row in table)
    {
        //write out table
    }
}

To get properties:

YourModel.GetType().GetProperties();

To get the name of a property:

property.Name;

To get the value of a property:

var result = YourModel.GetType().InvokeMember("NameOfProperty", BindingFlags.GetProperty, null, YourModel, null);

Some more well developed examples can be found in this file on GitHub: https://github.com/jamestharpe/Rolcore/blob/master/src/Rolcore/Reflection/ObjectExtensions.cs

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