2014-10-31 33 views
6

我想獲得支持呈現特定模型類型的所有視圖的列表。迭代ASP.NET MVC視圖以查找支持特定模型類型的所有視圖

僞代碼:

IEnumerable GetViewsByModelType(Type modelType) 
{ 
    foreach (var view in SomeWayToGetAllViews()) 
    { 
     if (typeof(view.ModelType).IsAssignableFrom(modelType)) 
     { 
     yield return view; // This view supports the specified model type 
     } 
    } 
} 

換句話說,因爲我有一個MyClass的模式,我想找到一個能夠支持使其所有視圖。即@model類型爲MyClass的所有視圖或其繼承鏈中的類型。

+0

順便說一句 - 有什麼目的? – Landeeyo 2014-10-31 19:05:05

+0

用於爲基於MVC的CMS創建「Wordpress-esque」模板系統的原型的一部分,其中可以將新模板簡單地放入項目中並在運行時解析。 – 2014-11-12 15:33:42

回答

6

根據我的發現,編譯的視圖不包含在程序集中,所以它不會在公園反射中散步。

在我看來,您最好的選擇是列出.cshtml剃鬚刀視圖,然後使用BuildManager類來編譯該類型,這將允許您獲取Model屬性類型。

這裏是尋找具有LoginViewModel的@Model類型的所有刀片觀點的例子:

var dir = Directory.GetFiles(string.Format("{0}/Views", HostingEnvironment.ApplicationPhysicalPath), 
    "*.cshtml", SearchOption.AllDirectories); 

foreach (var file in dir) 
{ 
    var relativePath = file.Replace(HostingEnvironment.ApplicationPhysicalPath, String.Empty); 

    Type type = BuildManager.GetCompiledType(relativePath); 

    var modelProperty = type.GetProperties().FirstOrDefault(p => p.Name == "Model"); 

    if (modelProperty != null && modelProperty.PropertyType == typeof(LoginViewModel)) 
    { 
     // You got the correct type 
    } 
} 
+0

是的,我最終做了這樣的事情。感謝您的幫助! – 2014-11-12 15:32:08

+0

歡迎您;) – 2014-11-12 15:33:40