7

인덱스 뷰에 자동 스캐 폴더를 쓰려고합니다. 모델 또는 뷰 모델 모음 (예 : IEnumerable<MyViewModel>)을 전달하고 머리글 (th 요소)에 DisplayName 특성을 사용하고 셀에 Html.Display(propertyName) (td 요소)을 사용하는 HTML 테이블을 가져올 수 있기를 바랍니다. . 각 행은 컬렉션의 항목 하나와 일치해야합니다.ASP.NET MVC : 컬렉션의 항목에 대한 ModelMetadata에 액세스합니다.

세부보기와 같이 하나의 레코드 만 표시하는 경우 ViewData.ModelMetadata.Properties을 사용하여 특정 모델의 속성 목록을 가져옵니다. 그러나 뷰에 전달하는 모델이 모델 또는 뷰 모델 객체의 집합이며 모델 또는 뷰 모델 자체가 아닌 경우 어떻게됩니까?

컬렉션의 특정 항목에 대해 ModelMetadata를 얻으려면 어떻게해야합니까?

public static class MyExtensions 
{ 
    public static ModelMetadata GetMetadata<TModel>(this TModel model) 
    { 
     return ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TModel)); 
    } 
} 

을 그리고 당신의보기 :

답변

6

간단한 확장 방법은 일을 할 수

<%@ Page 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewPage<System.Collections.Generic.IEnumerable<MyViewModel>>" %> 

<%-- Get metadata for the first item in the model collection --%> 
<%= Html.Encode(Model.ElementAt(0).GetMetadata().ModelType) %> 
+0

내가 필요한거야 즉, 감사합니다! – devuxer

관련 문제