Jay
Jay

Reputation: 2262

How to get the value of a ModelMetadata in ASP.NET Core?

I have a project that is written with C# on the top of ASP.NET Core 5.0 framework.

I am trying to render the razor views manually by accessing the data directly using ModelMetadata. In a view, I want to iterate through all the properties in the Html.ViewData.ModelMetadata and get the value of each property manually.

In the old ASP.NET MVC, I use to be able to access the value using the Model property on the ModelMetadata. With ASP.NET Core however, it seems that we have to get an instance of a ModelExplorer to be able to access the value of the ModelMetadata

Here is what I tried

foreach (ModelMetadata propertyMetadata in Html.ViewData.ModelMetadata.Properties)
{
    ModelExplorer explorer = propertyMetadata.GetModelExplorerForType(propertyMetadata.ModelType, null);

    // do something with explorer.Model

    // I also tried 
    ModelExplorer explorer2 = html.ViewData.ModelMetadata.GetModelExplorerForType(propertyMetadata.ModelType, null);
}

The explorer is returning the correct ModelType of the property but explorer.Model or explorer2.Model are always null in this case.

How do I correctly create the ModelExplorer which will give me a model value?

Upvotes: 0

Views: 2214

Answers (2)

DanCZ
DanCZ

Reputation: 313

    @foreach (var property in ViewData.ModelMetadata.Properties.Where(p => p.PropertyGetter(Model) != null)) {
        <p><b>@property.GetDisplayName()</b> <i>@(property.IsEnumerableType ? string.Join(',', property.PropertyGetter(Model)) : property.PropertyGetter(Model))</i></p>
    }

Upvotes: 0

Jay
Jay

Reputation: 2262

It turned out that I can get the value using the delegate PropertyGetter

Here is an example of what I did.

@{
    IEnumerable<ModelMetadata> properties = metadata.Properties.Where(metadata => metadata.ShowForDisplay).OrderBy(metadata => metadata.Order);
}

@foreach(var property in properties)
{
    <span>@(property.PropertyGetter(Model))</span>
}

Upvotes: 1

Related Questions