简体   繁体   English

ModelMetaData:如何获得“父” - 元数据?

[英]ModelMetaData: How to get “Parent”-Metadata?

In my view I call Html.EditFor() which triggers a custom editor-template for this datatype. 在我看来,我调用Html.EditFor()来触发此数据类型的自定义编辑器模板。 Additionally I pass some Metadata with it (and that's the part I don't like): 另外我传递了一些元数据(这是我不喜欢的部分):

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

The passed type (property Title) is of type 'Translation'. 传递的类型(属性Title)的类型为“Translation”。 Within the custom editor-template I have to read the passed metadata from the viewData in order to use it: 在自定义编辑器模板中,我必须从viewData中读取传递的元数据才能使用它:

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

Is there some way I could access the metadata directly within the custom editor-template? 有没有什么方法可以直接在自定义编辑器模板中访问元数据? Unfortunately, if I call the following within the editor-template, I won't get the same metadata-object (where for example the information if the Title-Property is required or not is missing): 不幸的是,如果我在编辑器模板中调用以下内容,我将无法获得相同的元数据对象(例如,如果缺少Title-Property的信息,则会丢失):

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

I would like to avoid to pass the metadata-object on each call... 我想避免在每次调用时传递元数据对象...

Thx for any tipps! 任何tipps的Thx! sl3dg3 sl3dg3

I think you're trying to get the metadata for the actual property for the EditorTemplate. 我想你正在尝试获取EditorTemplate的实际属性的元数据。

You can do this like this (inside the EditorTemplate): 你可以这样做(在EditorTemplate中):

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

"" means for MVC the current property. “”表示MVC当前属性。

You could try the following to access the parent metadata: 您可以尝试以下方法来访问父元数据:

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

不可否认,派对有点晚了,但是有一种更简单的方法来获取当前模型的模型元数据 - 它作为ViewData属性存在:

var metadata = ViewData.ModelMetadata;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM