I would like to get a list of all views that support rendering a specific model type.
我想获得支持呈现特定模型类型的所有视图的列表。
Pseudo code:
伪代码:
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
}
}
}
In other words, given that I have a MyClass model, I'd like to find all views that would support rendering it. I.e. all views where the @model type is MyClass, or a type in its inheritance chain.
换句话说,鉴于我有一个MyClass模型,我想找到支持渲染它的所有视图。即@model类型为MyClass的所有视图,或其继承链中的类型。
1 个解决方案
#1
7
Based on my findings the compiled views are not included in the assembly, so it's not going to be a walk in the park reflection.
根据我的发现,编译的视图不包含在集合中,所以它不会是在公园反射中散步。
In my opinion your best bet is going to be to list the .cshtml
razor views and then use the BuildManager
class to compile the type, which will allow you to get the Model property type.
在我看来,最好的选择是列出.cshtml razor视图,然后使用BuildManager类编译类型,这将允许您获取Model属性类型。
Here is an example of looking for all Razor views that have a @Model type of LoginViewModel:
下面是一个查找具有@Model类型的LoginViewModel的所有Razor视图的示例:
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
}
}
#1
7
Based on my findings the compiled views are not included in the assembly, so it's not going to be a walk in the park reflection.
根据我的发现,编译的视图不包含在集合中,所以它不会是在公园反射中散步。
In my opinion your best bet is going to be to list the .cshtml
razor views and then use the BuildManager
class to compile the type, which will allow you to get the Model property type.
在我看来,最好的选择是列出.cshtml razor视图,然后使用BuildManager类编译类型,这将允许您获取Model属性类型。
Here is an example of looking for all Razor views that have a @Model type of LoginViewModel:
下面是一个查找具有@Model类型的LoginViewModel的所有Razor视图的示例:
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
}
}