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 ?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With