9

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?

Aliostad
  • 80,612
  • 21
  • 160
  • 208
Salamander2007
  • 6,294
  • 8
  • 32
  • 26

1 Answers1

14

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"));
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    `Type.GetType("AppName.Models.MyViewModel")` always return null, but `Type.GetType("AppName.Models.MyViewModel, AppName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")` returns the correct type. Thanks for the tip! – Salamander2007 Apr 15 '11 at 11:45