ModelMetaData: How to get "Parent"-Metadata?
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
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.
You could try the following to access the parent metadata:
<%
var parentType = this.ViewData.ModelMetadata.ContainerType;
var metadata = ModelMetadataProviders.Current.GetMetadataForType(null, parentType);
%>
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;
精彩评论