我想获取支持渲染特定模型类型的所有 View 的列表。
伪代码:
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 模型,我想找到所有支持呈现它的 View 。 IE。 @model 类型为 MyClass 或其继承链中的类型的所有 View 。
最佳答案
根据我的发现,汇编 View 未包含在程序集中,因此它不会是在公园散步的反射(reflection)。
在我看来,您最好的选择是列出 .cshtml
razor View ,然后使用 BuildManager
类来编译类型,这将允许您获取模型属性类型。
下面是一个查找所有具有 @Model 类型 LoginViewModel 的 Razor View 的示例:
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
}
}
关于c# - 迭代 ASP.NET MVC View 以查找支持特定模型类型的所有 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26680881/