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?