ModelMetaData: How to get the "parent" -Metadata?

In my opinion, I call Html.EditFor (), which runs my own template template for this data type. In addition, I pass him some metadata (and what I don't like):

<% ModelMetadata metaTitle = ModelMetadataProviders.Current.GetMetadataForProperty(null, Model.GetType(), "Title"); %> <%: Html.EditorFor(x => Model.Title, new { metaData = metaTitle })%> 

The missing type (property name) is of type "Translation". Within a custom editor template, I need to read the passed metadata from viewData in order to use it:

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Translation>" %> // {...} if (ViewData["metaData"] != null) metaData = (ModelMetadata)ViewData["metaData"]; 

Is there a way to access metadata directly in a custom editor template? Unfortunately, if I call the following in the editor template, I will not get the same metadata object (where, for example, there is no information if the Title-Property is required or not):

 ModelMetadata metaData = ModelMetadataProviders.Current.GetMetadataForType(null, Model.GetType()); 

I would like to avoid passing the metadata object on every call ...

thanks for any tips! sl3dg3

+3
source share
3 answers

I think you are trying to get metadata for the actual property for EditorTemplate.

You can do it like this (inside EditorTemplate):

 var metadata = ModelMetadata.FromStringExpression("", ViewData); 

"" means the current property for MVC.

+7
source

To access parent metadata, you can try the following:

 <% var parentType = this.ViewData.ModelMetadata.ContainerType; var metadata = ModelMetadataProviders.Current.GetMetadataForType(null, parentType); %> 
+5
source

It’s clear that it’s a bit late for the party, however there is an easier way to get the model metadata for the current model - it exists as a property for ViewData :

 var metadata = ViewData.ModelMetadata; 
0
source

Source: https://habr.com/ru/post/900811/


All Articles