ModelMetaData: How to get “Parent”-Metadata?

南笙酒味 提交于 2019-12-12 13:33:30

问题


In my view I call Html.EditFor() which triggers a custom editor-template for this datatype. 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'. Within the custom editor-template I have to read the passed metadata from the 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 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):

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! sl3dg3


回答1:


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

You can do this like this (inside the EditorTemplate):

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

"" means for MVC the current property.




回答2:


You could try the following to access the parent metadata:

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



回答3:


Admittedly a little late to the party, however there is a simpler way to get the model metadata for the current model - it exists as a property of ViewData:

var metadata = ViewData.ModelMetadata;


来源:https://stackoverflow.com/questions/5089086/modelmetadata-how-to-get-parent-metadata

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!