我建議使用的方法是在您的模型(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頁中的編程。