2015-05-19 45 views
0

我正在爲我的類創建自定義Editor Templates。我想過濾所有的導航屬性。無論如何要實現這一點,而不使用命名約定爲我的屬性?在ViewDate.ModelMetaData.Properties中過濾導航屬性

我的局部視圖看起來是這樣的:使用布爾標誌

@foreach (var property in ViewData.ModelMetadata.Properties) 
{ 
    <div class="form-group form-inline"> 
     <div class="col-xs-5"> 
      @if (property.PropertyName.StartsWith("Z") || 
       property.PropertyName.Equals("thename", StringComparison.CurrentCultureIgnoreCase) 
       ){ 
       continue; 
      } 
      @Html.Label(property.DisplayName) 
      @Html.TextBox(property.PropertyName) 
     </div> 
     <div class="col-xs-5"> 

     </div> 
    </div> 
} 

回答

1

試圖顯示。如果該標誌設置爲「顯示」,則使用標籤和文本框顯示該屬性。

1

我建議使用的方法是在您的模型(POCO)上使用自定義屬性。使用該屬性來標記特殊屬性。在進入循環之前,您可以使用反射來獲得Dictionary<string, customAttribute>,其中string是模型上屬性的名稱,而customAttribute是應用於類的自定義屬性(請檢查null以處理未應用定製屬性的屬性)。我附加了一個演示這些概念的LinqPad腳本,並且您可以獲得很好的視覺效果以查看正在發生的事情。

void Main() 
{ 

    var obj = new MyCustomClass(); 
    var tModel = obj.GetType(); /*in your case this will probably be ModelMetadata.ModelType as below */ 
    //var tModel = ViewData.ModelMetadata.ModelType; 

    var pAttributes = tModel 
     .GetProperties() /*modify the parameter to determine whether you want public fields as well etc*/ 
     .ToDictionary(p => 
      p.Name, 
      p => ((MyCustomAttribute)p.GetCustomAttribute(typeof(MyCustomAttribute))) 
     ); 

    pAttributes.Dump(); 

    /*I'm using this to mimic your ViewData.ModelMetadata.Properties */ 
    var modelProperties = new[] { 
     new { PropertyName = "Age" }, 
     new { PropertyName = "Name" }, 
     new { PropertyName = "Height" }, 
     new { PropertyName = "Area" } 
    }.ToList(); 

    foreach (var property in modelProperties) 
    { 
     if (pAttributes.ContainsKey(property.PropertyName) && (pAttributes[property.PropertyName]?.HasSpecialTreatment ?? false)) 
      Console.WriteLine("I am special: " + property.PropertyName); 
     else 
      Console.WriteLine(property.PropertyName); 

    } 

} 

// Define other methods and classes here 
public class MyCustomClass 
{ 
    [MyCustomAttribute(HasSpecialTreatment = true)] 
    public string Name { get; set; } 
    [MyCustomAttribute(HasSpecialTreatment = false)] 
    public int Age { get; set; } 
    [MyCustomAttribute(HasSpecialTreatment = true)] 
    public int Height { get; set; } 
    public int Length { get; set; } 
    public int Area { get; set; } 
} 

public class MyCustomAttribute : Attribute 
{ 
    public bool HasSpecialTreatment = false; 
} 

一個缺點這種方法是,它依賴於反思,我會更快使用這種方法生成的模板,而不是每個頁面執行時對飛執行。

您正在使用哪個版本的MVC?更好的方法是使用ModelMetaDataProvider或IDisplayMetadataProvider,具體取決於MVC版本,以便在流水線初期提供元數據並簡化View頁中的編程。