Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ModelMetadata outside a view context?

I need to export some kind of data (build a file), so the data won't be produced (renderized) by Views but by pure C# code, ouside a view. But I need some ModelMetadata informations.

I ask also how to build a ModelMetadata inside unit tests, so also, outside Views ?

like image 855
Luciano Avatar asked Jul 18 '12 22:07

Luciano


1 Answers

Assuming you have a view model with some metadata:

public class MyViewModel
{
    [DisplayName("Bar")]
    public string Foo { get; set; }
}

you could retrieve this metadata like this:

ModelMetadata metadata = ModelMetadata.FromLambdaExpression<MyViewModel, string>(
    x => x.Foo, 
    new ViewDataDictionary<MyViewModel>()
);

Assert.AreEqual("Bar", metadata.DisplayName);

UPDATE:

As requested in the comments section here's how to obtain the metadata if only the type is known at runtime:

var type = typeof(MyViewModel);
var metadata = ModelMetadataProviders.Current.GetMetadataForType(null, type);

and if you want to get the metadata for a child property just specify the name of the property:

var type = typeof(MyViewModel);
var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(null, type, "Foo");
like image 133
Darin Dimitrov Avatar answered Sep 27 '22 15:09

Darin Dimitrov