0

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?

Jay
  • 1,168
  • 13
  • 41
  • Hi @Jay,I could not use `Html.ViewData.ModelMetadata.Properties` in asp.net core.How did you use that?Maybe you could check this answer:https://stackoverflow.com/a/59000216/11398810. – Rena Dec 11 '20 at 07:39
  • @Rena thanks for your help. I figured it out. Please check out my answer – Jay Dec 11 '20 at 15:00

2 Answers2

1

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>
}
Jay
  • 1,168
  • 13
  • 41
0
    @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>
    }
DanCZ
  • 187
  • 4
  • 10