Get Model Metadata from its class name

2020-07-06 08:21发布

问题:

I'm aware that we can access model meta data using

var metaData = ModelMetadataProviders.Current.GetMetadataForType(() => Model, Model.GetType());

What I'm looking for is a way to access model metadata just using it's class name, without it's instance (maybe something like ModelMetadataProviders.Current.GetMetadataForType(Model.GetType())). Is there an easy way to achieve that?

回答1:

You don't need an instance in order to access the metadata of a type:

var metaData = ModelMetadataProviders
    .Current
    .GetMetadataForType(null, typeof(SomeViewModel));

And if all you have is a string representing the type name you could load the type from this string:

var metaData = ModelMetadataProviders
    .Current
    .GetMetadataForType(null, Type.GetType("AppName.Models.MyViewModel"));