迭代ASP.NET MVC的观点找到支持特定型号类型的所有意见 [英] Iterate ASP.NET MVC views to find all views supporting a specific model type

查看:163
本文介绍了迭代ASP.NET MVC的观点找到支持特定型号类型的所有意见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得的支持呈现一个特定的模式类型的所有视图列表

I would like to get a list of all views that support rendering a specific model type.

伪代码:

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的,还是在其继承链类型。

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.

推荐答案

根据我的调查结果编制的意见不包括在装配的,所以它不会是在公园散步反思。

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.

在我看来你最好的选择将是列出 .cshtml 剃须刀的意见,然后用在 BuildManager 类编译类型,这将让你得到模型属性类型。

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.

下面是一个例如查找具有LoginViewModel的@Model类型的所有剃刀观点:

Here is an example of looking for all Razor views that have a @Model type of LoginViewModel:

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
    }
}

这篇关于迭代ASP.NET MVC的观点找到支持特定型号类型的所有意见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆